背景:在做一个用户上传图片(发布随笔),但是微信需要对图片进行验黄等检测,并规定图片尺寸在750*1334,所以要对图片进行等比例缩放。
(本来写在后端合适,1.是后端懒,2.后端些了一个,有时候图片尺寸大了,报内存不足,所以最后写在了小程序端)
https://mp.weixin.qq.com/cgi-bin/announce?action=getannouncement&key=11522142966rk3L2&version=1&lang=zh_CN&platform=2
这个写在 wx.chooseImage 里面
//let that = this;//在外部定义 //打印未处理的图片信息 wx.getFileInfo({ filePath: file.path, success: function (res) { console.log(res); } }) //-----压缩图片开始 (像素不超过750*1334) wx.getImageInfo({ src: file.path, success: function (res) { console.log(res); let cW = res.width, cH = res.height; let cWidth = cW,cHeight= cH; if ((cW / cH)<0.56){ //说明 要依高为缩放比例--0.56是 750/1334的结果 if (cH>1334){ cHeight = 1334; cWidth = (cW * 1334) / cH; } } else {//要依宽为缩放比例 if (cW > 750) { cWidth = 750; cHeight = (cH * 750) / cW; } } console.log(parseInt(cWidth));//计算出缩放后的宽 console.log(parseInt(cHeight));//计算出缩放后的高 that.setData({ cWidth: cWidth, cHeight: cHeight});//让canvas大小和要缩放的图片大小一致 let imageW = cWidth, imageH = cHeight, canvasId = "canvas", imagePath = res.path; const ctx = wx.createCanvasContext(canvasId); ctx.drawImage(imagePath, 0, 0, cW, cH, 0, 0, imageW, imageH); ctx.draw(false, setTimeout(function () { // 一定要加定时器,因为ctx.draw()应用到canvas是有个时间的 wx.canvasToTempFilePath({ canvasId: canvasId, x: 0, y: 0, width: imageW, height: imageH,
destWidth: imageW,
destHeight: imageH,
quality: 1, success: function (res) { console.log(res); //打印处理后的图片信息 wx.getFileInfo({ filePath: res.tempFilePath, success: function (res) { console.log(res); } }) }, }); }, 200)); } }); //-----压缩图片结束
wxml 中要加
<canvas class="canvas" canvas-id="canvas" style="width:{{cWidth}}px;height:{{cHeight}}px;"></canvas>
可以加些样式隐藏
visibility: hidden;position:absolute;z-index:-1; left:-10000rpx;top:-10000rpx;
一个等比缩放的效果:
参考 :
https://www.cnblogs.com/jonyellow/p/11727776.html
https://github.com/jonyellow/code-diary/