gpt4 book ai didi

javascript - Canvas,获取图片压缩大小和调整大小

转载 作者:行者123 更新时间:2023-11-30 16:36:50 25 4
gpt4 key购买 nike

我正在使用 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?

关于javascript - Canvas,获取图片压缩大小和调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32609371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com