微信小程序 压缩图片并上传
转自https://segmentfault.com/q/1010000012507519
wxml写入
1 2 3 | < view bindtap='uploadImg'>上传</ view > < image bindtap='uploadImg' data-number="0" src="{{ uploadPic[0] }}" alt="" mode="widthFix"></ image > < canvas style="width: {{cw}}px; height: {{ch}}px;" canvas-id="firstCanvas"></ canvas > |
JS参考
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | uploadImg(e) { let that = this ; console.log(e); let index = e.currentTarget.dataset.number; let uploadFile = '' ; //最后处理完,图片上传的图片地址 wx.chooseImage({ success(res) { console.log(res) const tempFilePaths = res.tempFilePaths; //获得原始图片大小 wx.getImageInfo({ src: res.tempFilePaths[0], success(res) { // console.log('获得原始图片大小',res.width) //console.log(res.height) var originWidth, originHeight; originHeight = res.height; originWidth = res.width; console.log(originWidth); //压缩比例 // 最大尺寸限制 var maxWidth = 1200, maxHeight = 600; // 目标尺寸 var targetWidth = originWidth, targetHeight = originHeight; //等比例压缩,如果宽度大于高度,则宽度优先,否则高度优先 if (originWidth > maxWidth || originHeight > maxHeight) { if (originWidth / originHeight > maxWidth / maxHeight) { // 要求宽度*(原生图片比例)=新图片尺寸 targetWidth = maxWidth; targetHeight = Math.round(maxWidth * (originHeight / originWidth)); } else { targetHeight = maxHeight; targetWidth = Math.round(maxHeight * (originWidth / originHeight)); } } //尝试压缩文件,创建 canvas var ctx = wx.createCanvasContext( 'firstCanvas' ); //当在组件里使用时,要使用var ctx = wx.createCanvasContext('firstCanvas',that); that是this的变量 ctx.clearRect(0, 0, targetWidth, targetHeight); ctx.drawImage(tempFilePaths[0], 0, 0, targetWidth, targetHeight); ctx.draw(); //更新canvas大小 that.setData({ cw: targetWidth, ch: targetHeight }); //保存图片 setTimeout( function () { wx.canvasToTempFilePath({ canvasId: 'firstCanvas' , success: (res) => { //写入图片数组 var uploadpic = "uploadPic[" + index + "]" ; // that.setData({ [uploadpic]: res.tempFilePath }); uploadFile = res.tempFilePath; //保存到相册 // wx.saveImageToPhotosAlbum({ // filePath: res.tempFilePath, // success: (res) => { // console.log(res) // }, // fail: (err) => { // console.error(err) // } // }) wx.uploadFile({ url: 'https://example.weixin.qq.com/upload' , //仅为示例,非真实的接口地址 filePath: uploadFile, name: 'file' , formData: { 'user' : 'test' }, success(res) { const data = res.data //do something } }) }, fail: (err) => { console.error(err) } }, this ) //注意这里this是否指向正确,that? }, 500); } }) } }) } |
后面还有一个写法 20210703
// 上传图片
async chooseImg() {
var _that = this;
const imgs = this.data.imgs;
const max_imgs_length = 1;
var oldCount = imgs.length;
const tempFilePaths = await this.$chooseImage(max_imgs_length, ['original']);
for (var i = 0; i < tempFilePaths.length; i++) {
// imgs.push(tempFilePaths[i]);
var tfp = tempFilePaths[i];
//获得原始图片大小
wx.getImageInfo({
src: tfp,
success(res) {
var originWidth, originHeight;
originHeight = res.height;
originWidth = res.width;
console.log(originWidth);
//压缩比例
// 最大尺寸限制
var maxWidth = 1200,
maxHeight = 1000;
// 目标尺寸
var targetWidth = originWidth,
targetHeight = originHeight;
//等比例压缩,如果宽度大于高度,则宽度优先,否则高度优先
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > maxWidth / maxHeight) {
// 要求宽度*(原生图片比例)=新图片尺寸
targetWidth = maxWidth;
targetHeight = Math.round(maxWidth * (originHeight / originWidth));
} else {
targetHeight = maxHeight;
targetWidth = Math.round(maxHeight * (originWidth / originHeight));
}
}
_that.setData({
cw: targetWidth,
ch: targetHeight
});
//尝试压缩文件,创建 canvas
var ctx = wx.createCanvasContext('ssd');
ctx.clearRect(0, 0, targetWidth, targetHeight);
ctx.drawImage(tfp, 0, 0, targetWidth, targetHeight);
ctx.draw(false, setTimeout(function () {
wx.canvasToTempFilePath({
canvasId: 'ssd',
fileType:'jpg',
destWidth:targetWidth,
destHeight:targetHeight,
quality:1.0,
success: (r) => {
imgs.push(r.tempFilePath);
_that.setData({
imgs: imgs
});
_that.loadPhoto(oldCount);
},
fail: (err) => {
console.error(err)
}
}, this)
}, 500));
//保存图片
}
})
}
}
wx.createCanvasContext()停止维护,可用下面方法代替
1 2 3 4 5 6 7 8 9 10 11 | let canvasBox = null ; // 写法一 canvasBox = wx.createCanvasContext( "ssd" ); // 写法二 wx.createSelectorQuery() . select ( "#ssd" ) .context(function (res) { console.log( "节点实例:" , res); // 节点对应的 Canvas 实例。 canvasBox = res.context; }) |
前端隱藏canvas
<view style="position:fixed;top:999999999999999999999rpx;">
<canvas id="ssd" canvas-id="ssd" style="width:{{cw}}px;height:{{ch}}px;"></canvas>
</view>
分类:
微信小程序
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?