shj
2022-04-11 b9657322e301ff165c988f88e44c26756c2059d7
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//base64转码(压缩完成后的图片为base64编码,这个方法可以将base64编码转回file文件)
function dataURLtoFile(dataurl) {
    let arr, mime, bstr, n, u8arr;
    arr = dataurl.split(',');
    mime = arr[0].match(/:(.*?);/)[1];
    bstr = atob(arr[1]);
    n = bstr.length;
    u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], { type: mime });
 
}
//压缩图片
function compressImg(file){
    // file = convertBase64UrlToBlob(file.content);
    const name = file.name;
    let files;
    let fileSize = parseFloat(parseInt(file['size'])/1024/1024).toFixed(2);
    let read = new FileReader();
    read.readAsDataURL(file);
 
    return new Promise(function(resolve){
        read.onload = function (e) {
            let img = new Image();
            img.src = e.target.result;
            img.onload = function(){
                //默认按比例压缩
                let w = this.width,
                    h = this.height;
                //生成canvas
                let canvas = document.createElement('canvas');
                let ctx = canvas.getContext('2d');
                let base64;
                // 创建属性节点
                canvas.setAttribute("width", w);
                canvas.setAttribute("height", h);
                ctx.drawImage(this, 0, 0, w, h);
                if(fileSize<1){
                    //如果图片小于一兆 那么不执行压缩操作
                    base64 = canvas.toDataURL(file['type'], 1);
                }else if(fileSize>1&&fileSize<2){
                    //如果图片大于1M并且小于2M 那么压缩0.5
                    base64 = canvas.toDataURL(file['type'], 0.5);
                }else{
                    //如果图片超过2m 那么压缩0.2
                    base64 = canvas.toDataURL(file['type'], 0.2);
                }
                // 回调函数返回file的值(将base64编码转成file)
                files = dataURLtoFile(base64); //如果后台接收类型为base64的话这一步可以省略
                let img = new File([files], name, {
                    type: 'image/jpeg',
                });
 
                //图片大小大于1024*1024,则再次压缩
                if (img.size > 1024*1024) {
                    compressImg(img).then(res=>{
                        img = res;
                        resolve(img)
                    })
                }else {
                    resolve(img)
                }
 
 
            };
        };
    })
}
 
 
//结尾处将该方法暴露出来供外部调用
export default {
    compressImg,
}