JavaScript本身没有提供压缩图片的方法,但是可以使用第三方库或API来实现。
一种常用的方法是使用canvas,将图片绘制到canvas上,再将canvas转换为图片格式。在绘制时可以控制canvas的尺寸,从而达到压缩图片的效果。以下是一个基础的示例代码:
function compressImage(file, maxWidth, maxHeight, quality, callback) {
const reader = new FileReader();
reader.onload = function () {
const img = new Image();
img.onload = function () {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
let width = img.width;
let height = img.height;
if (width > maxWidth) {
height *= maxWidth / width;
width = maxWidth;
}
if (height > maxHeight) {
width *= maxHeight / height;
height = maxHeight;
}
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height)<