小程序上传图片调整宽高比例4/3
// 上传图片回调
uplaodFile (files) {
// 文件上传的函数,返回一个promise
return new Promise((resolve, reject) => {
wx.getImageInfo({ // 查看图片
src: files.tempFilePaths[0],
success: (res) =>{
const {path, width, height} = res;
if(width/4 === height/3) { // 宽度合适直接上床
wx.uploadFile({
url: 'url', // 上传图片地址
filePath: files.tempFilePaths[0],
name: 'file',
header: {
'token': wx.getStorageSync('access_token')
},
success: (res) => {
console.log(res);
resolve({ urls: [JSON.parse(res.data).result] });
},
fail: (err) => {
reject(err);
}
});
return;
}
// 宽度填充至 4/3
wx.showLoading({
title: '填充图片中',
})
let newWidth = 0;
let newHeight = 0;
if(width/4 > height/3){
newWidth = width;
newHeight = width/4 * 3
} else {
newWidth = height/3 * 4
newHeight = height
}
this.setData({
canWidth:newWidth,
canHeight:newHeight
})
const ctx = wx.createCanvasContext('shareFrends');
ctx.width = width;
ctx.height = height;
ctx.fillStyle = '#fff'
ctx.fillRect(0, 0, newWidth, newHeight);
ctx.drawImage(path, (newWidth-width)/2, (newHeight-height)/2, width, height)
console.log(width, newWidth, height, newHeight)
ctx.draw(false, () => {
setTimeout(() => {
wx.canvasToTempFilePath({
x: 0,
y: 0,
width:newWidth,
height:newHeight,
destWidth: newWidth,
destHeight: newHeight,
canvasId: 'shareFrends',
fileType:'jpg',
quality:1,
success(res) {
wx.hideLoading()
wx.uploadFile({
url: config.host + '/api/mobile/oss/upload',
filePath: res.tempFilePath,
name: 'file',
header: {
'token': wx.getStorageSync('access_token')
},
success: (res) => {
console.log(res);
resolve({ urls: [JSON.parse(res.data).result] });
},
fail: (err) => {
reject(err);
}
});
},
fail(err){
reject(err);
}
})
})
})
wx.hideLoading()
}
})
});
},
<canvas style="background:red;position: fixed;top: -10000px;width:{{canWidth}}px;height:{{canHeight}}px" canvas-id="shareFrends"></canvas>
本文来自博客园,作者:懒惰ing,转载请注明原文链接:https://www.cnblogs.com/landuo629/p/15742572.html
【推荐】国内首个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速度为什么快?