forked from drone/command-center-dashboard

LGH
2025-03-26 4d16cee35c0cdf2c505d00a2a85364a0a09bcbae
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
 * @description: 图片压缩
 * @param {*} src 图片地址
 * @param {*} quality 压缩质量
 * @param {*} maxWidth 最大宽度
 * @param {*} callback 回调函数
 * @return {*}
 */
function compressImage(src, quality, maxWidth, callback) {
    const img = new Image();
    img.setAttribute('crossOrigin', 'Anonymous');
    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;
        }
 
        canvas.width = width;
        canvas.height = height;
        ctx.drawImage(img, 0, 0, width, height);
 
        const newData = canvas.toDataURL('image/jpeg', quality);
        // 使用atob()将base64转换为二进制字符串
        const binaryString = window.atob(newData.split(',')[1]);
        const mimeString = newData.split(',')[0].split(':')[1].split(';')[0];
        // 创建Blob对象
        const array = [];
        for (let i = 0; i < binaryString.length; i++) {
            array.push(binaryString.charCodeAt(i));
        }
        const blob = new Blob([new Uint8Array(array)], { type: mimeString });
 
        callback(blob);
    };
    img.src = src;
 
    return src;
}
 
export default function imageCompress(src, quality, maxWidth) {
    // 使用例子
    return compressImage(src, quality, maxWidth, function (blob) {
        // 创建一个新的图片URL
        const imageUrl = URL.createObjectURL(blob);
        // 可以在这里使用imageUrl,比如设置为img元素的src
        // document.getElementById('your-image-element').src = imageUrl;
        // 当不需要这个URL的时候,释放它
        URL.revokeObjectURL(imageUrl);
    });
}