微信小程序之小程序图片压缩

js里面
var requestCallback = function (err, data) {//请求结果
wx.getImageInfo({//获取这个图片 图片压缩
src: files[filescount],//需要获取的图片 图片选择不用我说了吧
success: function (res) {
var ctx = wx.createCanvasContext('photo_canvas');//使用一个canvas
var canvasWidth = res.width//原图宽度 
var canvasHeight = res.height;//原图高度
var tWidth = 800; //设置缩略图初始宽度 //可调
var tHeight = 640; //设置缩略图初始高度 //可调
if (canvasWidth > tWidth || canvasHeight > tHeight) {
//按比例计算出缩略图的宽度和高度
if (canvasWidth > canvasHeight * 1.8) {
tHeight = Math.floor(parseFloat(canvasHeight) * (parseFloat(tWidth) / parseFloat(canvasWidth)));
}
else {
tWidth = Math.floor(parseFloat(canvasWidth) * (parseFloat(tHeight) / parseFloat(canvasHeight)));
}
}
else {
tWidth = canvasWidth;
tHeight = canvasHeight;
}
//绘制新图
ctx.drawImage(files[filescount], 0, 0, tWidth, tHeight)
ctx.draw()
//下载canvas图片
setTimeout(function () {
wx.canvasToTempFilePath({
canvasId: 'photo_canvas',
success: function (res) {
var filePath = res.tempFilePath
var oldfilePath = files[filescount] //下面是我的调用腾讯云存储对象业务 不需要可删除
var Key = oldfilePath.substr(oldfilePath.lastIndexOf('/') + 1);
var yskeyCl = Key.split('.')
var yskey = yskeyCl[2] + '-ys.' + yskeyCl[3]
cos.postObject({
Bucket: config.Bucket,
Region: config.Region,
Key: yskey,
FilePath: filePath
}, function (err, data) {
JiaruFile(yskeyCl[2] + '.' + yskeyCl[3])//加入数据库
filescount = filescount + 1
zhixing()//这是并发控制 根据业务自行处理
});
},
fail: function (error) {
console.log(error)
}
})
}, 100)
}
})

}

页面要加上这个哦

猜你喜欢

转载自blog.csdn.net/qq_36170585/article/details/80223058
今日推荐