将图片压缩成指定大小


/**
 * 将图片压缩成指定大小
 * @param {string} base64Url base64或图片地址
 * @param {Number} width 图片宽度
 * @param {Number} height 图片高度 不传则使用宽度
 */
const compressImageToSize = (base64Url, width, height = "") => {
    if (!height) height = width
    const img = new Image();
    img.src = base64Url;
    return new Promise((resolve, reject) => {
        // 等待图片加载完成
        img.onload = () => {
            // 创建一个 Canvas 元素
            const canvas = document.createElement('canvas');

            canvas.width = width;
            canvas.height = height;

            // 获取绘制上下文
            const ctx = canvas.getContext('2d');

            // 在 canvas 上绘制图片
            ctx.drawImage(img, 0, 0, width, height);

            // 将 canvas 转换为新的 base64 图片
            const newBase64 = canvas.toDataURL('image/png');

            resolve(newBase64);
        };

        img.onerror = reject;
    });
}

猜你喜欢

转载自blog.csdn.net/zongxingfengyun/article/details/132282792