Resizing images on upload VS Resizing images on the fly

This is an interesting topic, simply because both methods can give you two completely different results.

Resizing on upload.

Using this method, we resize the image as soon as it is uploaded to the server. This way, we don’t have worry about resizing it at a later date. A basic drill down of the process:

  1. The user uploads an image.
  2. Our code resizes / crops the image into various different sizes (of course, all of these sizes are completely dependent on what our website needs).
  3. References to each version of the image are stored in the database like so:

image references stored inside the database

As you can see in the example above, we are storing two different versions of our uploaded image: The original and the resized thumbnail. This means that we can easily display our thumbnails images like so:

Resizing on the fly.

Dynamically resizing images involves the following process:

  1. The user uploads an image.
  2. Our code doesn’t modify the image. Instead we just take the original and store it.
  3. Later on, when the image is being displayed to the user, we pass the URL of the original to our resizer script, which resizes it down to a specified size.
  4. Our resizer script should then cache the generated thumbnail on disk for future use.

A small example of what the code might look like:

Which method is better?

Personally, I prefer to resize-on-upload. Why?

  1. It doesn’t force random visitors to bear the brunt of image processing. A user who is uploading something will obviously expect a slight delay – and that’s OK.
  2. If needs be, I can add the resize job to a queue (see Gearman, for example).
  3. Disk space is cheap. Image processing? Not so much! For example: In the past, I’ve witnessed 2MB pictures taking up to 0:00.15s in CPU processing time. That’s 0:00.15s per picture! What if I have a gallery and I need to create 20 thumbnails on the fly?
  4. If the cache fails for whatever reason (or if it doesn’t exist), dynamically generating thumbnails will become a painful experience for both the server and the end-user. A while back, I remember somebody on Stackoverflow referring to it as a self-inflicted DoS attack (obviously, the extent of the damage will depend on how many visitors you typically see, which is why so many Mom & Pop websites get away with not caching).
  5. If, for whatever reason, I need to change the thumbnail dimensions, I still have the original on file. It might be a bit of a pain to generate them all, but that’s a risk I’m willing to take.

Facebook Comments