Javascript 画布,压缩并调整图片大小

Javascript 画布,压缩并调整图片大小,javascript,jquery,canvas,compression,image-resizing,Javascript,Jquery,Canvas,Compression,Image Resizing,我正在使用FileReader在中显示与输入类型文件一起上载的文件。当文件被放到字段中时,我需要压缩文件并调整其大小。我使用了以下代码: 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; // Ma

我正在使用
FileReader
中显示与输入类型文件一起上载的文件。当文件被放到字段中时,我需要压缩文件并调整其大小。我使用了以下代码:

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;
编辑:显示完整代码

压缩后的文件保存在
result\u image\u 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
}
查看此处了解更多信息:

为什么首先要将文件传递到文件读取器?据我所知,您正在使用
readAsDataURL
方法,不是吗?如果是这样,为什么不直接使用
URL.createObjectURL(input.files[0])
?此外,要检测方向,您必须将图像数据加载到
img
元素中,但正如您所注意到的,某些设备会给出错误的值,即高度和宽度。如果您确实使用捕获,一个解决方案是检查
window.orientation
属性,但您不能确定照片拍摄的方向与用户离开输入表单的方向相同。对于生成的文件大小,是否需要将其保留为dataURL?如果将其转换回blob,您将节省约37%。我使用readAsDAtaURL yes显示压缩和调整大小后上载的图片。我不使用
URL.createObjectURL(input.files[0])
,因为如果我理解这个函数的含义,我就不想使用BLOB。对于结果大小,我需要显示压缩后的图片,以便使用新大小显示新图片。对于我发现可能很好的方向,我将尝试。你可以看到我的所有代码,我仍然不明白为什么你不想使用blob(它非常接近你得到的输入的文件对象),它将是一个步骤,你将能够得到文件的真实数据大小,并保存base64编码版本的37%。谢谢,这是可行的!不是真实尺寸,但非常接近。