【发布时间】:2015-09-17 15:48:08
【问题描述】:
我正在使用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 获取上传图片的方向吗?因为有些设备的人像图片是横向显示的。
谢谢
【问题讨论】:
-
一开始为什么要把文件传给 FileReader?据我了解,您使用的是
readAsDataURL方法,不是吗?如果是这样,为什么不直接使用URL.createObjectURL(input.files[0])?此外,要检测方向,您必须将图像数据加载到img元素中,但正如您所注意到的,有些设备会给您错误的值,即哪个是高度,哪个是宽度。如果您确实使用了捕获,一种解决方案是检查window.orientation属性,但您不能确定图片是在用户离开输入表单时的相同方向拍摄的。 -
对于生成的文件大小,是否需要将其保留为 dataURL ?如果将其转换回 blob,您将节省大约 37%。
-
我使用readAsDAtaURL yes来显示压缩和调整大小后上传的图片。我不使用
URL.createObjectURL(input.files[0]),因为如果我了解此功能的含义,我不想使用 BLOB。对于结果大小,我需要显示压缩的图片,以便新图片具有新的大小。对于我发现exif.js 的方向可能很好,我会尝试。 -
你可以看到我所有的代码here
-
我还是不明白你为什么不想使用blob(它真的很接近你得到的输入的File对象),它会少一步,你就可以得到文件的真实数据大小,并节省了base64编码版本的37%。
标签: javascript jquery canvas compression image-resizing