图片上传,压缩方法
1、点击图片上传,拿到图片,转化base64,然后在执行图片压缩
addImg() {
let _this = this;
plus.gallery.pick(function (path) {
plus.io.resolveLocalFileSystemURL(path,function (entry) {
entry.file(function (file) {
let files = {
src: '',
name: file.name
};
let reader = new plus.io.FileReader();
reader.readAsDataURL(file); // 读出base64
reader.onloadend = function (e) {
_this.canvasDataURL(e.target.result,{
quality: 0.7
},function (base64Codes) {
files.src = base64Codes;
_this.fileUp(files);
});
};
_this.$toast.loading({
duration: 10000,// 持续展示toast
forbidClick: true,// 禁用背景点击
loadingType: 'spinner',
message: '正在上传...'
});
});
});
},function (err) {
},null);
},
2、图片压缩的方法
canvasDataURL(path,obj,callback) {
let img = new Image();
img.src= path;
img.onload= function () {
let that = this; //默认按比例压缩
let w = that.width,
h = that.height,
scale = w / h;
w = obj.width || w;
h = obj.height || (w / scale);
let quality = 0.7; // 默认图片质量为0.7
//生成canvas
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
// 创建属性节点
let anw = document.createAttribute('width');
anw.nodeValue= w;
let 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值越小,所绘制出的图像越模糊
let base64 = canvas.toDataURL('image/jpeg',quality);
// 回调函数返回base64的值
callback(base64);
};
},