2006-03-03 · in Tech Notes · 455 words

There are several traps it's easy to fall into when scaling images for use on web pages. Here's an explanation of what can go wrong, and how to avoid it.

Original image

Here's the image we're going to start with, taken with my old digital camera in Mallorca a couple of years ago. You'll probably have better-quality source material, but this is sufficient for this demonstration.

Original image

Scaling down

Now, suppose we want a version that's 100 pixels high to use as a thumbnail.

Here's it scaled down in two different ways. The first image was scaled using a cubic interpolation filter — the correct way. The second used a "fast" resize filter that just picks out single pixels rather than doing any interpolation.

100-pixel tall, scaled with cubic filter 100-pixel tall, scaled with fast filter

Look at the sides of the green box, the dials in the middle and the flowers at the bottom right. While the low-detail areas on both images (like the background) look similar, the fast resize results in severe pixellation on high-contrast areas.

Scaling in the browser

The same problem can be caused inadvertently by doing image scaling in the user's web browser. This is typically caused by specifying width and height attributes on an img element that are not the actual size of the image — in this case, most browsers will use a "fast" resize algorithm, and will produce very poor results. Here's what the above scaling looks like when done by the web browser:

Original image, scaled to 100-pixel height
in browser

Scaling images down in the browser is an especially bad thing, because it means you're shipping data to the user that will be immediately thrown away — which makes the page load more slowly than it should do.

Scaling more than once

Now look at these images:

300-pixel tall, scaled down and back up
with cubic filter 300-pixel tall, scaled down and back up
with fast filter

These are the result of scaling the small images back up again to the original size — again, the cubic interpolation filter is the first image, and the fast filter the second. The cubic-filtered version is significantly blurrier than the original, since the first scaling step throws away information. The fast-filtered version has suffered even more from pixellation.

Avoiding the problems

To avoid the problems above, you should be able to follow these rules: