Canvas,获取图片压缩后调整大小

Canvas, get the size of picture compressed and resized

我正在使用 FileReader<div> 中显示使用输入类型文件上传的文件。当文件被拖放到现场时,我需要压缩文件并调整他的大小。我使用了这段代码:

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;

编辑:完整代码是here

压缩完成的文件保存在result_image_obj,但是在显示这个base64图片之前,我需要检查一下最终图片的大小。所以如果尺寸大于 500kb 我需要再次压缩图片。

有没有办法获取canvas生成的base64图片的大小(b, kb, mb..)?

另外一个问题:用FileReader可以获取上传图片的方向吗?因为有些设备的人像图片是横向显示的。

谢谢

您可以使用以下方法找到粗略的图像尺寸:

var size = newImageData.length * 3 / 4; // size in bytes

if (size > 500 * 1024) {  // more than 500 kb
   // do something
}

查看此处了解更多信息: Base64 length calculation?