Resizing images with Javascript

  • Pascal Helfenstein

Is image resizing still a server task?

Usually when you are implementing an image upload, you have to decide whether you use GD or ImageMagic. On a Javascript heavy project, I was facing the same decision and decided to go a different path. I decided to resize the images in the client with Javascript.

If you choose this approach you must be aware that it will only work on Browsers that support Canvas. It basically boils down to the question if you need to support anything lower than IE 9. If not you are good to go. After the image is resized, you can upload it with ajax and store it on the filesystem of your server. One advantage of this approach, is of course, the smaller upload size.

Resizing an Image with Javascript is fairly simple, the key points are:

How to create an Image Object

var img = new Image();

img.onload = function() {

    // Start resizing

};

img.src = src;

Draw an image with a certain size on a Canvas

ctx.drawImage(image, 0, 0, 1024, 576);

Fill content of a canvas into an image

$('#outputImage').attr('src', canvas.toDataURL("image/jpeg"));

The image will be filled with base64 encoded data

<img id="outputImage" src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGB......=">

Demo


Tell us what you think