JS使用Canvas压缩图片

暂未实现压缩到指定文件大小
也可以是用于插件https://github.com/WangYuLue/image-conversion

/**
 * 压缩图片
 * @param {type} filePath 图片路径
 * @param {type} scale 压缩比例
 */
compressImage(filePath,scale){
    const vm = this;
    const img = new Image();  
    img.src = filePath;// 传过来的图片路径在这里用。  
    img.onload = function () {  
        const that = this;  
        console.log(that.width,that.height);
        //生成比例   
        let w = that.width*scale,  
            h = that.height*scale;
        console.log(w,h);
        //生成canvas  
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = w;
        canvas.height = h;
        ctx.drawImage(that, 0, 0, w, h);
        //1最清晰,越低越模糊。有一点不清楚这里明明设置的是jpeg。弹出 base64 开头的一段 data:image/png;却是png。哎开心就好,开心就好  
        const base64 = canvas.toDataURL('image/jpeg', 1);
        // console.log(base64);
        const blob = vm.base64ToBlob(base64,'image/jpeg')
        const href = window.URL.createObjectURL(blob); //图片压缩后的blob src
        console.log(href);
    }  
},
/**
 * base64转bolb
 * @param {type} urlData base64
 * @param {type} type 类型image/png||image/jpeg
 */
base64ToBlob(urlData, type) {
    let arr = urlData.split(',');
    let mime = arr[0].match(/:(.*?);/)[1] || type;
    console.log(mime);
    // 去掉url的头,并转化为byte
    let bytes = window.atob(arr[1]);
    // 处理异常,将ascii码小于0的转换为大于0
    let ab = new ArrayBuffer(bytes.length);
    // 生成视图(直接针对内存):8位无符号整数,长度1个字节
    let ia = new Uint8Array(ab);
    for (let i = 0; i < bytes.length; i++) {
      ia[i] = bytes.charCodeAt(i);
    }
    return new Blob([ab], {
      type: mime
    });
},

你可能感兴趣的:(JS使用Canvas压缩图片)