function compressImage(srcOriginalImage, maxWidth = 200 ,maxHeight = 200) {
// 创建 canvas
const c = document.createElement('canvas');
c.style.display = 'none';
const body = document.querySelector('body');
body.appendChild(c);
var ctx = c.getContext("2d");
// 释放canvas
function releaseCanvas(){
c.remove();
}
// 创建要绘制的Image对象
var img = new Image();
img.crossOrigin = "anonymous";
img.src = srcOriginalImage;
return new Promise(resolve => {
// 等待img加载完毕
img.onload = function () {
// 与backgournd-size:contain效果相同
if (img.width / img.height < maxWidth / maxHeight) {
c.height = img.height;
if (img.height > maxHeight) {
c.height = maxHeight;
}
c.width = img.width / img.height * c.height;
} else {
c.width = img.width;
if (img.width > maxWidth) {
c.width = maxWidth;
}
c.height = img.height / img.width * c.width;
}
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, c.width, c.height);
const content = c.toDataURL();
releaseCanvas();
resolve(content);
};
});
}
压缩图片
最新推荐文章于 2024-07-24 19:28:54 发布