A design patter: don’t resize images during uploads

An established practice in web applications is to resize user images during uploads: I am suggesting a different approach instead, which relies in creating on-the-fly the requested size thumb.

The history

Most web applications require the users to upload some images.

The nasties developers will just tell the users to prepare beforehand an image of the correct size, so that no more processing is necessary and the image can be shown as it is.

But of course we as developers always try to help our users, don’t we, and the next solution is the dynamic resizing.

The dynamic resizing

This procedure means that the user uploads an image of more or less whatever size and proportions, and we process it immediately, using image processing libraries to create the required size image.

We can even create different sizes (i.e. small thumb, normal size, big version for zoom) and we can decide if we store or not the original one.

I’ve seen this approach in many web applications, especially at the beginning of my web development career.

But lately I’ve come to appreciate a different approach instead: the on-demand dynamic resizing.

The on-demand dynamic resizing

For a start, you always save the original image, possibly checking that is big enough to cover all possible uses (e.g. if a user uploads a 200x200px, that may not be enough for the “zoom” version).

Then, in your code, you replace your image “src” attribute with an helper / service that creates the required version of the tag. For example, something like:

<img src="<?php $this->getResizedImage("/img/users/176/image_01.jpg", "400", "300")" />

Note: this is just some generic PHP and does not refer to any specific framework.

Of course, to avoid recreating the resized image each time, that method should also save it into a cache folder, and use it if already existing.
public function getResizedImage ($img, $width, $height = 0) {
    $resizedImagePath = $width . "_" . $height . "_" . $img;
if (file_exists($resizedImagePath)) {
return $resizedImagePath;
}
$this->createResizedImage($img, $width, $height);

return $resizedImagePath;
}

This is a very naive code and should be extended for better naming, and possibly to also check the  last modified date of the saved image file (i.e. allow for cache expiration).

But I think you get the picture… in fact, you can get all the pictures you want 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *