asimes
asimes

Reputation: 5894

Resizing <img> causing slowness

I am working on a site that will have a lot of images inside of boxes (divs) sorted as a grid (absolute positioning). I have noticed that resizing the images to fit the boxes causes the site to slow down significantly. There are a lot of images (342), but I don't understand why this is the case as the site runs quickly when I don't resize them.

Please note: I plan on implementing the dynamic resizing of the boxes in the future. I mention this to avoid the answer of saving every image at another size. I am interested in knowing the cause of the slowdown not a different method of implementation.

The grid is initially made up of boxes (divs) that are 150px * 150px. The grid is in the <body> and initially has no images (just empty divs). When the body has loaded, a JavaScript function places the images into their appropriate box. The JavaScript function relies on PHP for getting the images from a database as well as for resizing. Here are the steps for that section of PHP:

1.) PHP gets image filename from database.

2.) PHP gets image dimensions (in pixels) and saves them into two variables. I'll call them x and y here.

3.) I change x and y so that the image will fit 150px * 150px (or whatever initial value I assign to the boxes' initial dimensions).

4.) I use echo to write document.getElementById("PHP given Id").innerHTML = '<img src="PHP given filename" style="width:PHP x value; height:PHP y value"/>';.

If I comment out step 3 in my code the site runs quickly (that is commenting out the part that changes x and y from the image default dimensions). I have also tried setting the width and height attributes of the <img> instead of inline CSS but that does not solve the slowness issue.

Upvotes: 0

Views: 137

Answers (2)

vfsoraki
vfsoraki

Reputation: 2307

use gd library in php to load image dynamically and resize it, then use header function in php to tell browser that you are sending an image (not text). the you output resized image.

with this approach, you could use something like this for <img> tags:

    <img src="script.php?file=someFile" style="width: 150px; height: 150px;" />

with this, you dont need to create thumbnail for each image.

Upvotes: 0

c2h5oh
c2h5oh

Reputation: 4560

Resizing images takes quite a bit of computing power, hence the slowdown. Best thing you could do is resize images with PHP and save thumbnails, so you only do it once.

Upvotes: 6

Related Questions