小程序上传服务器图片压缩,微信小程序压缩图片并上传到服务器(拿去即用)...

这段代码主要展示了如何在微信小程序中实现图片压缩。通过创建canvas,按比例压缩图片到指定宽度,然后将压缩后的图片保存为临时文件,并上传到服务器。过程中使用了wx.getImageInfo、wx.createCanvasContext、wx.canvasToTempFilePath和wx.uploadFile等API。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**压缩图片*/compressionImage(tempFilePaths, params) {

let that= thiswx.getImageInfo({

src: tempFilePaths[0],

success:function(res) {var ctx = wx.createCanvasContext('photo_canvas');//设置canvas尺寸

var towidth = 500; //按宽度500px的比例压缩

var toheight = Math.trunc(500 * res.height /res.width);

that.setData({

canvas_h: toheight

})

ctx.drawImage(tempFilePaths[0], 0, 0, res.width, res.height, 0, 0, towidth, toheight)

that.createMap(ctx, params);

}

})

},/**创建画布并上传图片*/createMap(ctx, params) {

let that= this;

ctx.draw(true, function() {

wx.showLoading({

title:'压缩中',

})

setTimeout(()=>{

wx.canvasToTempFilePath({

canvasId:'photo_canvas',

fileType:"jpg",

success:function(res) {

wx.hideLoading();

wx.uploadFile({

url: app.globalData.baseUrl+ '/wechat/want/addWant',

filePath: res.tempFilePath,

name:'file',

formData: {'parameters': JSON.stringify(params)

},

success:function(res) {

console.log("state:" +JSON.parse(res.data).state)if (JSON.parse(res.data).state === 1) {

wx.showToast({

title:'发布成功',

duration:2000,

icon:"none",

success() {

setTimeout(function() {

wx.navigateBack({

delta:1,

})

},1000);

}

})

}

},

fail(res) {

console.log("fail" +res)

}

})

},

fail(res) {if (res.errMsg === "canvasToTempFilePath:fail:create bitmap failed") {

console.log("导出map失败")

}

}

},this)

},200);

})

},

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值