微信小程序:压缩图片&转base64
需求:用户上传头像,头像base64后提交给后端,后端无法接受大于64KB的图片,所以前端需要压缩后base64转码再传递给后端
获取用户上传的图片,使用wx.chooseImage时,sizeType必须选择为compressed,否则sizeType会默认['original', 'compressed'],即[原图,压缩图]success获取用户上传图片的信息主要是需要获取URL,大小貌似微信小程序的API只能压缩jpg格式的图片,所以小伙伴们需要注意这个问题
wx.chooseImage({// 选择图片
count:1,
sizeType: ['compressed'],
success: function(res) {
wx.showLoading({// 开load
title: '上传中',
mask:true,
success(){
console.log('图片原始大小:' + res.tempFiles[0].size);
console.log('图片原始路径:'+res.tempFiles[0].path);
let format = res.tempFiles[0].path.split('.'); //查询判断图片类型
if (format[format.length - 1] == 'jpg'){
that.compress(res.tempFiles[0]);
} else if (format[format.length - 1] == 'JPG') {
that.compress(res.tempFiles[0]);
} else {
app.ClickLoading();
that.prompt('请上传jpg格式图片', 'loading');
}
}
})
},
})
当格式正确后,进入下一步(判断图片大小是否符合要求),判断图片大小是否符合要求(小于64K)wx.compressImage这里有个需要注意的,它是无损压缩,所以quality的值可以设置最小(quality决定压缩的大小,值越小,压缩得越小)获取到压缩后的临时路径,用于转码
compress: function (res) {// 图片压缩
var that = this;
console.log(res);
if (res.size >= 63000) {// 当图片大于64K,压缩,这里我限制写得比较小
wx.compressImage({// 图片压缩
src: res.path,
quality: 1,
success(res) {
that.SizeImg(res);
}
})
} else {
that.base(res.path); // 当图片小于64K,开base64
}
},
SizeImg: function (res) {// 查询图片大小
let that = this;
wx.getFileInfo({ //查询压缩后的图片大小
filePath: res.tempFilePath,
success(r) {
console.log('压缩后的文件大小:' + r.size);
console.log('压缩后的临时路径:' + res.tempFilePath);
if(r.size >= 63000){
app.ClickLoading();
that.prompt('图片过大', 'loading');
}else{
that.base(res.tempFilePath);
}
}
})
},
接下来就是base64转码了,这里需要使用wx.getFileSystemManager(img).readFile的API接口,使用canvas太慢,且代码臃肿微信小程序不提供FileReader()方法,所以不使用结束!
base:function(img){
let that = this;
wx.getFileSystemManager(img).readFile({
filePath: img, //选择图片返回的相对路径
encoding: 'base64', //编码格式
success: res => { //成功的回调
console.log(res)
}
})
},
接下来结束了?等一下,给大家看一个好东西
wx.chooseImage({ //获取本地接口
success:res=>{
this.urlTobase64(res.tempFilePaths[0])
}
})
urlTobase64(url){//接下来,把临时路径作为一个请求的url,把数据返回格式设置成arraybuffer
wx.request({
url:url,
responseType: 'arraybuffer', //最关键的参数,设置返回的数据格式为arraybuffer
success:res=>{
//把arraybuffer转成base64
let base64 = wx.arrayBufferToBase64(res.data);
//不加上这串字符,在页面无法显示的哦
base64 = 'data:image/jpeg;base64,' + base64
//打印出base64字符串,可复制到网页校验一下是否是你选择的原图片呢
console.log(base64)
}
})
}
大坑代码提供者:Aleyn.大佬 如果用编辑器写出来的时候,可以发现也可以用,但是太天真了,在真机上会疯狂报错!!! 大坑,勿踏
|