// 使用 HTML5 Canvas 和 JavaScript 压缩图片的示例代码
function compressImage(file, maxWidth, maxHeight, quality) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = function(event) {
const img = new Image();
img.onload = function() {
let elem = document.createElement("canvas");
let ctx = elem.getContext("2d");
// 计算新的宽度和高度以保持比例
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;
}
}
elem.width = width;
elem.height = height;
// 将图像绘制到 canvas 上
ctx.drawImage(img, 0, 0, width, height);
// 将 canvas 转换为压缩后的图片
elem.toBlob(function(blob) {
resolve(blob);
}, 'image/jpeg', quality);
};
img.src = event.target.result;
};
reader.onerror = function(error) {
reject(error);
};
reader.readAsDataURL(file);
});
}
// 示例用法
const fileInput = document.querySelector('input[type="file"]');
fileInput.addEventListener('change', async function(event) {
const file = event.target.files[0];
try {
const compressedFile = await compressImage(file, 800, 600, 0.7); // 最大宽度800px,最大高度600px,质量70%
console.log(compressedFile); // 这是压缩后的文件对象
} catch (error) {
console.error('Error compressing image:', error);
}
});
compressImage 函数:
file(要压缩的图片文件)、maxWidth(最大宽度)、maxHeight(最大高度)和 quality(压缩质量,范围从 0 到 1)。FileReader 读取图片文件,并将其加载到 Image 对象中。Canvas 绘制调整大小后的图像,并通过 toBlob 方法将图像转换为压缩后的 Blob 文件。示例用法:
change 事件,当用户选择图片时,调用 compressImage 函数进行压缩。console.log 或其他方式处理。上一篇:js 压缩工具
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站