Search code examples
phpimage-resizingbandwidth

Gauging the relative importance of client-side image resizing vs bandwidth considerations


My site is using a php function to resize images so the browser doesn't have to do it:

function resizeImg($img, $newW, $newH, $rotateTrue) {
  //image resize code, then

  return base64_encode($image_data);
}

where the function is called like this:

<img src="data:image/png;base64,<?= resizeImg('myImg', newWidth, newHeight, 1); ?>" alt="pic">

No problems. However, the image data that is returned is sizeable. When I inspect the element in Chrome, > 1kB of encoding data is returned per resized image.

This is fine for a scattered image here and there, but what if you have a huge table? For example, one table on my site is > 1500 rows with one image per row. EACH image is currently resized by the browser, which I know is not ideal. However, if I resized every one of these 1500 images using my server-side resize function, I would add roughly this amount of encoded data:

1500 images x ~1.1 kB encoding data per image = 1650 kB

to this table.

For a high-performance site, which should I give more importance to, bandwidth savings (i.e., resize client side) or browser-savings (i.e., resize server-side)?


Solution

  • tl;dr BOTH

    The main issue with your approach is that you are open to very easy DDoS attacks by multiplying the computational impact of a page request to your server, since you are generating new images on the fly. Needless to say that the code you posted and the term high performance are not going well together because of this problem.

    Another issue is the fact that clients are not able to cache the images you sent them (unless you cache the complete webpage you delivered) since they are inlined via base64.

    The solution is simple. Resize the images to a set of predefined sizes and store them on your server. Deliver those various sizes to the client and let the client to the rest of the work. Of course you have to properly configure your server for client side caching of those image files.

    You could use the new <picture> element (picturefill for old browsers) on the client side to support multiple devices with different resolutions. Of course some scaling will happen but you cannot generate images for absolutely every device out there.


    If your question is only regarding upscaling, just don’t do it at all. Not on the server and not on the client side. Upscaled images simply look ugly.