Web Programming: Proportional Image Resize in JavaScript

Proportional Image Resize in JavaScript

Socialbrowse currently shows summaries of shared links that have an ATOM or RSS feed. The feeds come with images of all sizes and we have to change the height and width to fit within the alloted space. CSS has max-width and max-height parameters but they have issues in IE and they don’t keep original proportions of the image! To resize and keep the proportions we use javascript.

This javascript resize function will do a proportional resize to keep the given <img> within the given max height and max width (maxh and maxw). Feel free to copy and use it in any way you like.

May 30th, 2006

If you need to force images to fit within your web page layout you really only have two options:

Resize images on the server.

Resize images on the client.

Resize images on the server

If you have the resources, resizing on the server is probably the best solution depending on your requirements. This solution requires server-side software to manipulate the images and store the altered image for future reference. For Ruby, the RMagick library does an excellent job with this. However, manipulating images on the server is a very expensive operation. If you are on a shared server, like I am, this may not be an option for you. But don’t worry, there is an alternative below.

Resize images on the client

The other option for resizing images involves using Javascript on the client-side to resize them on the fly. This solution has two drawbacks:

It requires Javascript.

It requires downloading the full image, whereas the server-side resizing will result in much smaller image sizes.

If these two drawbacks are ok with you, then read on 🙂

To resize the images, you need to first create a javascript function to do the resizing. Feel free to use this one that I wrote:

This function has been tested successfully against IE 6 and Firefox 1.5 (if you can verify this against others, please let me know and I will update this list). One thing worth mentioning is that only the longest side of the image needs to be resized to fit your maximum size. The aspect ratio will still be maintained by the web browser.

The resize function expects an image id and an optional maximum size. For this to work properly, the resizing must only occur after the image was loaded. This can be enforced by using the onload attribute of the image tag.