画布,获取压缩和调整大小的图片大小

时间:2015-09-16 13:01:31

标签: javascript jquery canvas compression image-resizing

我使用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,我需要再次压缩图片。

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

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

由于

1 个答案:

答案 0 :(得分:2)

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

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

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

点击此处了解更多信息: Base64 length calculation?