画布,得到图片的大小压缩和调整大小

Canvas, get the size of picture compressed and resized

本文关键字:压缩 调整 画布      更新时间:2023-09-26

我使用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;

EDIT:完整代码在这里

压缩完成的文件保存在result_image_obj中,但在显示此base64图像之前,我需要检查最终图像的大小。因此,如果大小大于500kb,我需要再次压缩图片。

是否有办法获得画布生成的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长度计算?