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>

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

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

Above will obtain the file and we can trigger that with a change event binding with jQuery. 
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");

Friday, January 18, 2013

[UnderscoreJS] - check for Null values inside a JSON object

Let say you have a JSON object:

var my_object = {
  'name' : 'Catherine',
  'email' : '',
  'city' : 'Vancouver',
  'age' : null,
  'school' : 'Simon Fraser'

To look for any null values might be a bit of work, since we will have to get the list of attributes, and loop through them.

With UnderscoreJS, we are able to validate the object easily.

_.contains(_.values(my_object), null)

_.value(my_object) will return a list of values in your object, in this case it returs:

['Catherine', '', 'Vancouver', null, 'Simon Fraser']

_.contains(list, value) returns true if the list contains the value or else return false.

For more: