需求:
图片上传时,要求必须是720*720大小的图片,但是用camera拍出来的照片大小不固定,有的手机是720*720,有的就是1080*1080,还有480*480的
解决办法:
将图片转换成canvas,再在canvas中操作,最后将canvas转换图片导出
先大概贴一下html代码和js中的data
<view style='height:292px;width:292px;'> <camera wx:if="{{complated!=true}}" device-position="front" flash="off" class='face-image'></camera> <!-- 给用户展现的图片 --> <image wx:if="{{complated==true}}" class='face-image' src='{{faceUrl}}'></image> <!-- 辅助裁剪的canvas,不显示给用户,因为720太大,界面放不下 --> <canvas canvas-id='image-canvas' style='width:720px;height:720px;position:fixed;top:-10000px;left:-10000px;'></canvas> </view>data: { complated: false, // 拍照是否完成 faceUrl: '' // 图片的临时路径},重点来了~
1.拍照
(检查拍到的图片大小是否是720*720,是的话,不用处理,如果不是,就调用我们自己写的图片处理函数loadTempImagePath进行处理)
const ctx = wx.createCameraContext()// 拍照ctx.takePhoto({ quality: 'normal', success: (res) => { var tempImagePath = res.tempImagePath; // 拍的照片的临时地址 // 获取图片详情 wx.getImageInfo({ src: tempImagePath, success: res => { // 检查图片宽高等于720 if (res.width == 720 && res.height == 720) { that.setData({ complated: true, faceUrl: tempImagePath }) return; }else{ that.loadTempImagePath(tempImagePath) } }, fail: fail => { console.log('获取拍照信息失败了') that.loadTempImagePath(tempImagePath) } }) } })2.图片处理函数loadTempImagePath
// 参数options是拍照获取到的临时路径loadTempImagePath(options) { var that = this; // 矩形的位置 (设置了要求的大小:720) var image_x = 0; var image_y = 0; var image_width = 720; var image_height = 720; //过渡页面中,图片的路径坐标和大小 var canvas = wx.createCanvasContext("image-canvas") canvas.drawImage(options, 0, 0, image_width, image_height) wx.showLoading({ title: '数据处理中...', icon: 'loading', mask: true, duration: 10000 }) // 这里有一些很神奇的操作,总结就是MD拍出来的照片规格居然不是统一的过渡页面中,对裁剪框的设定 canvas.strokeStyle = '#f4f8f9'; canvas.strokeRect(image_x, image_y, image_width, image_height) canvas.draw( true, function(){ wx.canvasToTempFilePath({ //裁剪对参数 canvasId: "image-canvas", // x: image_x, //画布x轴起点 // y: image_y, //画布y轴起点 // width: image_width, //画布宽度 // height: image_height, //画布高度 // destWidth: image_width, //输出图片宽度 // destHeight: image_height, //输出图片高度 success: function (res) { console.log('图片处理成功了',res) that.setData({ complated: true, faceUrl: res.tempFilePath }) wx.hideLoading() }, fail: function (e) { wx.hideLoading() wx.showToast({ title: '出错啦...', icon: 'loading' }) } }) } ) },小程序













