Reputation: 525
I'm using FileReader
to display in a <div>
a file uploaded with an input type file. When the file is dropped in the field, I need to compressed the file and resize him. I used this code :
var width = source_img_obj.naturalWidth;
var height = source_img_obj.naturalHeight;
var quality = 90;
var maxWidth = 2000; // Max width for the image
var maxHeight = 2000; // Max height for the image
var ratio = 0; // Used for aspect ratio
// Check if the current width is larger than the max
if (width > maxWidth){
ratio = maxWidth / width; // get ratio for scaling image
height = height * ratio; // Reset height to match scaled image
width = width * ratio; // Reset width to match scaled image
}
// Check if current height is larger than max
if (height > maxHeight){
ratio = maxHeight / height; // get ratio for scaling image
width = width * ratio; // Reset width to match scaled image
height = height * ratio; // Reset height to match scaled image
}
var cvs = document.createElement('canvas');
cvs.width = width;
cvs.height = height;
var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0, width, height);
var newImageData = cvs.toDataURL(mime_type, quality/100);
var result_image_obj = new Image();
result_image_obj.src = newImageData;
EDIT : FULL code is here
The finished file compressed is saved in result_image_obj
, but before display this base64 image, I need to check the size of the final picture. So if the size is larger than 500kb I need to compress again the picture.
Is there a way to get the size (b, kb, mb..) of a base64 picture generated by canvas ?
Another question : Can we get the orientation of the picture uploaded with FileReader ? Because with some device portait picture are displayed in landscape orientation.
Thanks
Upvotes: 1
Views: 2057
Reputation: 20373
You can find rough image size using:
var size = newImageData.length * 3 / 4; // size in bytes
if (size > 500 * 1024) { // more than 500 kb
// do something
}
Look here for more info: Base64 length calculation?
Upvotes: 2