Friday, April 19, 2013

[Javascript] Photo Upload - Client-side image manipulation with HTML5 canvas

Sometimes our smartphones take amazing photos, but often they would be quite large.  If for some reason, you want to downsize or resize the images before upload to server (uploading large image and resize on server side is rather expensive...), we can use HTML5 canvas to help do the magic.

First get the file from <input>

HTML:
<input type="file" id="uploadInput" name="files[]" style="visibility: hidden" accept="image/*" >

JS:
var file = document.getElementById('uploadInput').files[0];

Above will obtain the file and we can trigger that with a change event binding with jQuery. 
jq('#uploadInput').change(function(){  
var file = document.getElementById('paFileUploadInput').files[0];
  // do things with file}


With the File object, we are able to draw it onto a HTML5 canvas and do whatever we want with it!

In this case, we can to resize it to at least 500 x 500.


    var canvas = document.createElement('canvas');

    var ctx = canvas.getContext('2d');


    var img = new Image;


    var MAX_WIDTH = 500;


    var MAX_HEIGHT = 500;

    img.onload = function() { 
     // code to manipulate the image
    }
    var theURL = window.URL || window.webkitURL;
    img.src = theURL.createObjectURL(file);


the img.onload function will execute when we set the src attribute of the element.  The src is obtained by createObjectURL on the very last line. 

Now, lets continue with the onload function. Since we want to resize the image, we shall get a new set of image dimension.


    var width = _width = img['width'];
    var height = _height = img['height'];
    if (width > height){
         if (width > MAX_WIDTH){ 
             height *= MAX_WIDTH / width;
             width = MAX_WIDTH;               
            }
     }
      else {
         if (height > MAX_HEIGHT) {
              width *= MAX_HEIGHT / height;
              height = MAX_HEIGHT;  
              }
      } 

With the new width and height, lets update the canvas size:

      canvas['width'] = width;
     canvas['height']= height;


And draw our image onto the canvas.
ctx.drawImage(img, 0, 0, _width, _height, 0, 0, width, height);

Lastly, we need to get the new base64 data of the new image to send to server:
var dataurl = canvas.toDataURL("image/jpeg");

No comments:

Post a Comment