Resize an image before upload using JQuery.



function handlePhoto(evt)
{
var file = evt.target.files[0];
var FR = new FileReader();           
var img = new Image();
var can = document.createElement("canvas");
var ctx = can.getContext('2d');
FR.onload = function(e) {
img.src = = e.target.result;
img.onload = function() {      
var ctx = can.getContext('2d');
//Set canvas 
var max_size = 750,// pull max size from a site config
width = this.width,
height = this.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
can.width = width;
can.height = height;
ctx.drawImage(this, 0, 0,width,height);
var dataURI = can.toDataURL(); 
dataURI = dataURI.replace(/^data:image\/(png|jpg);base64,/, "");
        console.log('New Image source: ' + dataURI);                         
}
};       
FR.readAsDataURL( this.files[0] );
}

No comments:

Post a Comment