2014/04/06

Resizing images with SimpleUploads

One of the recent additions to the SimpleUploads plugin is the ability to process the images on the client before they are uploaded to the server.

At the moment I've added two options to allow automatic conversion of bmp images as well as rejecting images that are bigger than the defined dimensions, but it's easy to customize your page so that you can for example resize the images on the client and that way it will be much faster.

Of course this isn't a magical solution: the resizing is done using a canvas, so if any animated image will lose the animation, and I'm not sure about transparency in gif and pngs.

Anyway, I've created a Sizing demo showing the different options:

1) Don't restrict the uploads in anyway

2) Use only a server-side script. If you want to limit the size of images you should always use this kind of setup as a last option so that even if the image isn't resized on the client it's correctly processed and validated on the server.

3) Check the size and reject them

4) Reescale the image on the client, that way it's uploaded much faster.

I might add this option directly in the plugin, but for the momento I think that it's good to have the option to use your own code and that way you can tweak it to better fit your requirements.

The code itself is simple, this is it:

function scaleImage(ev)
{
 var data = ev.data,
  editor = ev.editor;

 var img = data.image;

 // maximum size allowed for images
 var maxX = 400;
 var maxY = 300;
 var imgX = img.width;
 var imgY = img.height;

 if (imgX == 0 || imgY == 0)
 {
  alert("Ops, the image doesn't seem to be valid");
  ev.cancel();
  return;
 }

 // if it's smaller, get out
 if (imgX <= maxX && imgY <= maxY)
  return;

 var ratio = imgX / imgY;
 if ((maxX / maxY) > ratio)
  maxX = Math.round(maxY * (ratio));
 else
  maxY = Math.round(maxX / (ratio));

 var canvas = document.createElement("canvas");
 canvas.width = maxX;
 canvas.height = maxY;

 var ctx = canvas.getContext('2d');
 ctx.drawImage(img, 0, 0, maxX, maxY);

 if ( /\.jpe?g$/.test(data.name))
 {
  // You could adjust here the quality of jpg
  evData.file = canvas.toDataURL("image/jpeg", 0.9);
 }
 else
  data.file = canvas.toDataURL("image/png");
}

4 bis) Use a high quality resize as provided by the ImageCrop plugin that provides a dialog to allow the user to crop & resize the images before they are uploaded to the server. This plugin also allows to restrict the images to a maximum dimensions in case the user didn't select any sizing option in the dialog