base64图片压缩 js
时间: 2023-10-26 21:05:56 浏览: 105
您可以使用JavaScript中的canvas将图片压缩为base64格式。以下是一个示例代码:
```javascript
function compressImage(file, maxWidth, maxHeight) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(event) {
const img = new Image();
img.src = event.target.result;
img.onload = function() {
const canvas = document.createElement('canvas');
let width = img.width;
let height = img.height;
if (width > height) {
if (width > maxWidth) {
height *= maxWidth / width;
width = maxWidth;
}
} else {
if (height > maxHeight) {
width *= maxHeight / height;
height = maxHeight;
}
}
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
const compressedBase64 = canvas.toDataURL('image/jpeg', 0.7); // 压缩质量为0.7
resolve(compressedBase64);
};
};
reader.onerror = function(error) {
reject(error);
};
});
}
```
阅读全文