微信小程序如何将图片调整为5:4
时间: 2023-05-25 14:06:19 浏览: 218
1. 首先需要获取原图片的宽度和高度。
2. 然后根据5:4的比例,算出目标图片的宽度和高度。
3. 判断图片是横向还是纵向的,如果是纵向的,我们需要把高度缩短到目标高度,然后按比例调整宽度;如果是横向的,则需要把宽度缩短到目标宽度,然后按比例调整高度。
4. 最后使用canvas将原图片绘制到目标图片上,并保存到本地。
示例代码如下:
```javascript
// 获取原图片的宽度和高度
wx.getImageInfo({
src: '原图片路径',
success(res) {
const originalWidth = res.width;
const originalHeight = res.height;
// 计算目标图片的宽度和高度
const targetWidth = Math.floor(originalHeight * 5 / 4);
const targetHeight = originalHeight;
// 判断图片是横向还是纵向
let x = 0;
let y = 0;
let width = 0;
let height = 0;
if (originalWidth > originalHeight) {
x = Math.floor((originalWidth - originalHeight * 5 / 4) / 2);
y = 0;
width = targetWidth;
height = targetHeight;
} else {
x = 0;
y = Math.floor((originalHeight - originalWidth * 4 / 5) / 2);
width = originalWidth;
height = Math.floor(originalWidth * 4 / 5);
}
// 使用canvas绘制图片
const ctx = wx.createCanvasContext('myCanvas');
ctx.drawImage('原图片路径', x, y, width, height, 0, 0, targetWidth, targetHeight);
ctx.draw(false, () => {
// 保存图片到本地
wx.canvasToTempFilePath({
canvasId: 'myCanvas',
success(res) {
console.log(res.tempFilePath);
}
});
});
}
});
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)