Archive

Archive for July, 2015

Create thumbnail with HTML5 Canvas

July 29, 2015 Leave a comment

The HTML5 Canvas comes with the drawImage and toDataURL functions which are very usefull when it comes to Image manipulation. In fact, you can use those functions in order to resize or crop your images client side. Here a function I wrote which resize and image and sends back the base64 string :

 

function resizeImageBase64(img, width, height) {
   var canvas = document.createElement('canvas'),
   ctx = canvas.getContext('2d');

   canvas.width = width;
   canvas.height = height;

   ctx.drawImage(img, 0, 0, width, height);

   var str = canvas.toDataURL('image/jpeg', quality);
   canvas = null; // in order to garbage collect those elements
   ctx = null; // it helps if you launch that function on several bug size images
   return str;
}
Categories: Uncategorized