Control the size of images in Javascript to be uploaded to the server
To enhance the download and upload speed as well as lowering the memory space in server we need to control the size of the images that we would upload to the server.
The following javascript code snippet will help us to limit the image size.
var resizeImage = function(settings){
var file = settings.file;
var maxSize = settings.maxSize;
var reader = new FileReader();
var image = new Image();
var canvas = document.createElement('canvas');
var dataURItoBlob = function(dataURI){
var bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
atob(dataURI.split(',')[1]) : unescape(dataURI.split(',')[1]);
var mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
var max = bytes.length;
var ia = new Uint8Array(max);
for(var i=0;i height){
if(width > maxSize){
height *= maxSize/width;
width = maxSize;
}else if(width<200){
height = 200*height/width;
width = 200;
}
}else{
if(height> maxSize){
width *= maxSize/height;
height = maxSize;
}else if(height<200){
width = 200*width/height;
height = 200;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image,0,0,width,height);
var dataUrl = canvas.toDataURL('image/jpeg');
return dataURItoBlob(dataUrl);
};
return new Promise(function(ok,no){
if(!file.type.match(/image.*/)){
no(new Error('Not an image'));
return;
}
reader.onload = function(readerEvent){
image.onload = function(){return ok(resize());};
image.src = readerEvent.target.result;
};
reader.readAsDataURL(file);
});
}
Now, to use the above code snippet in our javascript, we need the image file. We can use file selector to choose the required image file:
The html code: