//图片压缩 参数 file 图像质量 回调函数
photoCompress: function(file, qualityObj, callback) {
var ready = new FileReader();
ready.readAsDataURL(file);
ready.onload = function () {
var re = this.result;
utils.canvasDataURL(re, qualityObj, file.name, callback)
}
},
canvasDataURL: function(path, obj, name, callback) {
var img = new Image();
img.src = path;
img.onload = function () {
var that = this;
// 默认按比例压缩
var w = that.width,
h = that.height,
scale = w / h;
w = obj.width || w;
h = obj.height || (w / scale);
var quality = 0.7; // 默认图片质量为 0.7
//生成 canvas
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// 创建属性节点
var anw = document.createAttribute("width");
anw.nodeValue = w;
var anh = document.createAttribute("height");
anh.nodeValue = h;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
ctx.drawImage(that, 0, 0, w, h);
// 图像质量
if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
quality = obj.quality;
}
// quality 值越小,所绘制出的图像越模糊
var base64 = canvas.toDataURL('image/jpeg', quality);
var arr = base64.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
let file = new File([new Blob([u8arr], {type: mime})], name);
// 回调函数返回 base64 的值
callback(file);
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于