js 等比压缩图片
时间: 2023-08-06 18:15:42 浏览: 59
可以使用canvas实现js等比压缩图片。具体步骤如下:
1. 创建一个Image对象,将需要压缩的图片加载进来。
2. 使用canvas创建一个画布,并设置画布的宽度和高度。
3. 计算图片的宽高比例,根据比例计算出压缩后的图片宽度和高度。
4. 在画布上绘制压缩后的图片,并使用toDataURL()方法将画布内容转换为base64编码的字符串。
5. 将转换后的字符串发送给服务器或者保存到本地。
以下是一个简单的示例代码:
```javascript
function compressImage(sourceImg, maxWidth, maxHeight) {
return new Promise((resolve, reject) => {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const img = new Image();
img.src = sourceImg;
img.onload = () => {
const imgWidth = img.width;
const imgHeight = img.height;
const ratio = Math.min(maxWidth / imgWidth, maxHeight / imgHeight);
const drawWidth = imgWidth * ratio;
const drawHeight = imgHeight * ratio;
canvas.width = drawWidth;
canvas.height = drawHeight;
context.drawImage(img, 0, 0, drawWidth, drawHeight);
const base64Data = canvas.toDataURL('image/jpeg');
resolve(base64Data);
};
img.onerror = reject;
});
}
```
其中,sourceImg为原始图片的地址或base64编码的字符串,maxWidth和maxHeight为压缩后的最大宽度和高度。使用该函数可以将图片等比压缩,并返回base64编码的字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)