移动应用中用户往往需要上传照片,但是用户上传的照片尺寸通常很大,而手机的流量却很有限,所以在上传前对图像进行压缩是很有必要的。
原生应用可以直接对文件进行处理,网页应用就没有这个优势了。不过 canvas
的出现给出一条新的思路,将图像按照比例绘制到画布上,最后将绘制完成的画布以 base64
编码方式发送到服务端,再由服务端进行解析还原成图片。由于进行处理的过程较为复杂,于是 localResizeIMG
就孕育而生了,它简化了前端压缩图片的步骤,减轻了前端工程师的工作负担。Github:https://github.com/think2011/localResizeIMGlocalResizeIMG 插件的优势:
经过大量测试,特别适合在移动设备上使用
基于原生 JavaScript 编写,支持
AMD 规范
localResizeIMG 的获取方式:
GitHub:https://github.com/think2011/localResizeIMG
NPM命令:npm install lrz压缩图片:lrz(file, [options]);
file 通过 input:file 得到的文件,或者直接传入图片路径
[options] 这个参数允许忽略
width {Number} 图片最大不超过的宽度,默认为原图宽度,高度不设定时会适应宽度
height {Number} 图片的最大高度,默认为原图高度
quality {Number} 图片压缩质量,取值 0 - 1,默认为 0.7
fieldName {String} 后端接收的字段名,默认:file
返回结果:promise 对象
then(rst) 处理成功后执行
rst.formData 后端可处理的数据
rst.file 压缩后的file对象,如果压缩率太低,将会是原始file对象
rst.fileLen 生成后的图片的大小,后端可以通过此值来校验是否传输完整
rst.base64 生成后的图片base64,后端可以处理此字符串为图片,也可以直接用于 img.src = base64
rst.base64Len 生成后的base64的大小,后端可以通过此值来校验是否传输完整
rst.origin 也就是原始的file对象,里面存放了一些原始文件的信息,例如大小、日期等
异步上传:processData 和 contentType 必须设为 false,否则服务端不会响应
<form class="addphoto">
<div class="file-input">
<div class="am-u-sm-12 am-u-md-12 am-u-lg-12 am-text-left">
<input accept="image/*" id="{{array.str}}" type="file" onchange="angular.element(this).scope().uploadImage(this.files,$(this)[0].id)" />
</div>
</div>
</form>
$scope.lrzImg = function(data, params) {
lrz(data, {
width: 400,
quality: 0.5
}).then(function(rst) {
for (m in $scope.imgArray) {
if ($scope.imgArray[m].str === params) {
$scope.imgArray[m].image.push(rst.base64);
break;
}
}
$scope.$apply();
}).catch(function(err) {
console.log(err)
});
}