小智 55
我刚刚开发了一个名为JIC的javascript库来解决这个问题.它允许您使用javascript在客户端100%压缩jpg和png,无需外部库!
你可以在这里试试这个演示:http://makeitsolutions.com/labs/jic 并在这里获取资源:https://github.com/brunobar79/JIC
小智 7
我迟到了,但这个解决方案对我很有用.基于此库,您可以使用一个函数 - 设置图像,质量,最大宽度和输出格式(jepg,png):
function compress(source_img_obj, quality, maxWidth, output_format){
var mime_type = "image/jpeg";
if(typeof output_format !== "undefined" && output_format=="png"){
mime_type = "image/png";
}
maxWidth = maxWidth || 1000;
var natW = source_img_obj.naturalWidth;
var natH = source_img_obj.naturalHeight;
var ratio = natH / natW;
if (natW > maxWidth) {
natW = maxWidth;
natH = ratio * maxWidth;
}
var cvs = document.createElement('canvas');
cvs.width = natW;
cvs.height = natH;
var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0, natW, natH);
var newImageData = cvs.toDataURL(mime_type, quality/100);
var result_image_obj = new Image();
result_image_obj.src = newImageData;
return result_image_obj;
}
Run Code Online (Sandbox Code Playgroud)
我在这里阅读了一个实验:http://webreflection.blogspot.com/2010/12/100-client-side-image-resizing.html
理论上说,您可以在上传之前使用canvas来调整客户端上的图像大小.原型示例似乎只适用于最近的浏览器,但有趣的想法...
但是,我不确定使用canvas来压缩图像,但你肯定可以调整它们的大小.
如果您正在寻找执行客户端图像压缩的库,则可以查看以下内容:compress.js。这基本上可以帮助您纯粹使用JavaScript压缩多个图像并将它们转换为base64字符串。您可以选择设置最大大小(以MB为单位)以及首选图像质量。