画布,得到图片的大小压缩和调整大小
Canvas, get the size of picture compressed and resized
我使用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长度计算?
相关文章:
- 内部分区字体大小获胜'调整浏览器窗口大小时不会随媒体查询而更改
- 使用压缩的JavaScript文件(不是运行时压缩)
- 调整窗口大小时,可拖动的对象会出现在容器外部
- ExtJS——在展开/折叠时调整面板高度
- 压缩phonegap中ios的图像插件
- Chrome应用程序调整窗口大小保持纵横比
- 如何自动调整标签的高度以适应内容
- 导航栏没有调整到浏览器屏幕的大小
- 调整屏幕大小后不显示子菜单
- 使用JavaScript根据窗口/视口的高度动态调整图像大小
- 合并两个数组,重新调整循环js
- Morris.js折线图x轴标签在调整大小后消失
- 调整缩放窗口高度提升缩放
- 将图片上传到服务器,服务器调整图片大小并进行压缩,最后将结果发送到源CDN
- 压缩&调整用户上传图像的大小
- Facebook风格上传的图片大小调整和压缩
- 如何从富文本压缩图像和调整图像大小
- 在Node/AngularJS应用程序中调整和压缩AJAX图像
- 调整大小&在Web Worker中压缩图像.我可以用一块画布吗
- 画布,得到图片的大小压缩和调整大小