移动端上传图片压缩图片(canvas)

创建CompressPicture.ts文件

class CompressedPicture {
    /**
     * 压缩图片
     * @param file 
     * @returns 
     */
    compressImg(file) {
        let files;
        let fileSize: number = Number(Number(parseInt(file["size"]) / 1024 / 1024).toFixed(2));
        let read = new FileReader();
        read.readAsDataURL(file);
        let that = this;
        return new Promise(function (resolve, reject) {
            read.onload = function (e: any) {
                let img = new Image();
                img.src = e.target.result;
                img.onload = function () {
                    //默认按比例压缩
                    let img: any = this;
                    let w = img.width,
                        h = img.height;
                    //生成canvas
                    let canvas = document.createElement("canvas");
                    let ctx: any = 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 if (fileSize > 2 && fileSize < 5) {
                        //如果图片超过2m并且小于5M  那么压缩0.2
                        base64 = canvas.toDataURL(file["type"], 0.2);
                    } else {
                        base64 = canvas.toDataURL(file["type"], 0.1);
                    }
                    // 回调函数返回file的值(将base64编码转成file)
                    files = that.dataURLtoFile(base64, file.name); //如果后台接收类型为base64的话这一步可以省略
                    resolve(files);
                };
            };
        });
    }
    /**
     * 将base64编码转成file
     */
    dataURLtoFile(dataUrl, fileName) {
        let 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], fileName, { type: mime });
    }
}
export default CompressedPicture;
import CompressPicture from "@/components/CompressPicture";
let compressPicture = new CompressPicture();
compressPicture.compressImg(files[0]).then((result: any) => {
        //压缩完成之后的file
        console.log(result)
});

你可能感兴趣的:(移动端上传图片压缩图片(canvas))