<canvas style="width:600px;height:600px;position:fixed;left:9000px;" id="picCanvas" type="2d"></canvas>
注:ios 的canvas尺寸不能太大,要不然会出现空白,最好在700以内
afterRead() {
uni.chooseImage({
count: 6, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['camera','album'], //从相机或相册选择
success: async (res: any) => {
let f: any = res;
const _this:any = this;
console.log(res)
for ( let i=0;i<f.tempFiles.length;i++){//for循环解决异步问题
let item = f.tempFiles[i]
wx.showLoading({title:'图片加载...'})
await this.$CompressedFiles(item.path,_this).then((data:any)=>{
let index:any = item.path.lastIndexOf("//tmp/")
let fileName:string = item.path.substring(index+6,item.path.length);
this.fileList.push({path:item.path,base64:data,fileName:fileName});
wx.hideLoading()
})
}
}
});
}$CompressedFiles(path:string,_this:any){
return new Promise((resolve, reject)=>{
wx.getImageInfo({
src:path,
success:function(res){
//图片的宽度和高度
let canvasRatio = 1.1;
let path = res.path;
let picWidth:any = res.width //图片原始长宽
let picHeight:any = res.height
let quality = 1;
while (picWidth > 800 || picHeight > 800) { // 保证宽高在400以内
picWidth = Math.trunc(res.width / canvasRatio)
picHeight = Math.trunc(res.height / canvasRatio)
canvasRatio = canvasRatio + 0.1;
quality = 0.6;
}
const query = wx.createSelectorQuery()
query.select('#picCanvas').fields({
node: true,
size: true
}).exec(async (res) => {
try{
let canvas = res[0].node
let ctx = canvas.getContext('2d')
let dpr = wx.getSystemInfoSync().pixelRatio
_this.canvasWidth = picWidth / dpr
_this.canvasHeight = picHeight / dpr
canvas.width = picWidth
canvas.height = picHeight
const img = canvas.createImage()
img.src = path
img.onload = () => {
ctx.drawImage(img, 0, 0, picWidth, picHeight);
setTimeout(async () => {
await wx.canvasToTempFilePath({
fileType: "jpg",
canvas: canvas,
destWidth: picWidth,
destHeight: picHeight,
quality,
success: async function (res:any) {
console.log(2,ctx)
//转为base64
await wx.getFileSystemManager().readFile({
filePath: res.tempFilePath,
encoding: "base64",
success: function (res1) {
console.log(3, res.tempFilePath)
let base64:any = ('data:image/png;base64,' + res1.data);
resolve(base64)
},
fail:(res)=>{
uni.showToast({
title:'图片转为base64失败',
icon:'none'
})
}
})
},
fail: function (res) {
console.log(res)
reject(res)
}
}, _this)
}, 600)
}
}catch (e) {
}
})
}
})
})
}版权声明:本文为qq_25103439原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。