JS 压缩图片转base64
时间: 2023-09-02 16:08:42 浏览: 47
可以使用 JavaScript 的 FileReader 和 Canvas API 实现图片压缩并转换为 base64 编码。
首先,使用 FileReader 将图片读取为 Blob 对象,然后使用 Canvas API 将图片压缩为指定的宽度和高度,最后将压缩后的图片转换为 base64 编码。
以下是一个示例代码:
```
function compressAndConvertToBase64(file, maxWidth, maxHeight, callback) {
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);
callback(compressedBase64);
}
}
}
```
其中,参数 `file` 是要压缩的图片文件,`maxWidth` 和 `maxHeight` 分别是压缩后的图片最大宽度和高度,`callback` 是压缩完成后的回调函数。压缩后的图片质量可以通过 `toDataURL` 方法的第二个参数来控制,值越小表示压缩后的图片质量越低。
使用示例:
```
const fileInput = document.querySelector('#file-input');
fileInput.addEventListener('change', function() {
const file = fileInput.files[0];
compressAndConvertToBase64(file, 800, 600, function(base64) {
console.log(base64);
});
});
```
以上代码可以将选择的文件压缩为最大宽度为 800、最大高度为 600 的图片,并将压缩后的图片转换为 base64 编码输出到控制台。