js上传图片大小压缩

/*
    file:文件(类型是图片格式),
    obj:文件压缩后对象width, height, quality(0-1)
    callback:容器或者回调函数
*/
let photoCompress = function (file) {
    return new Promise((resolve, reject) => {
        try {
            let that = this;
            let ready = new FileReader();
            /*开始读取指定File对象中的内容. 读取操作完成时,返回一个URL格式的字符串.*/
            ready.readAsDataURL(file);
            ready.onload = function () {
                let re = this.result;
                //开始压缩
                canvasDataURL(re, (base64) => {
                    let minFile = base64UrlToFile(base64, file.name)
                    resolve(minFile)
                })
            }
        } catch (error) {
            reject(error)
        }
    })
}

/*利用canvas数据化图片进行压缩*/
/*图片转base64*/
let canvasDataURL = function (path, callback) {
    let obj = {}

    let img = new Image();
    img.src = path;
    img.onload = function () {
        let that = this;   //指到img
        // 默认按比例压缩
        let w = that.width,
            h = that.height,
            scale = w / h;
        w = obj.width || w;
        h = obj.height || (w / scale);
        let quality = 0.4;  // 默认图片质量为0.4
        //生成canvas
        let canvas = document.createElement('canvas');
        let ctx = canvas.getContext('2d');
        // 创建属性节点
        let anw = document.createAttribute("width");
        anw.nodeValue = w;
        let anh = document.createAttribute("height");
        anh.nodeValue = h;
        canvas.setAttributeNode(anw);
        canvas.setAttributeNode(anh);
        ctx.drawImage(that, 0, 0, w, h);
        // 图像质量
        if (obj.quality && obj.quality === 1 && obj.quality === 0) {
            quality = obj.quality;
        }
        // quality值越小,所绘制出的图像越模糊
        let base64 = canvas.toDataURL('image/jpeg', quality);
        // 回调函数返回base64的值
        callback(base64);
    }
}

/*这里转file*/
let base64UrlToFile = function (urlData, filename) {
    let arr = urlData.split(','),
        mime = arr[0].match(/:(.*?);/)[1],  // 去掉url的头,并转化为byte
        bstr = atob(arr[1]),    // 处理异常,将ascii码小于0的转换为大于0
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    // return new Blob([u8arr], { type: mime });
    //转file
    return new File([u8arr], filename, { type: mime });
}

export default photoCompress
发布了78 篇原创文章 · 获赞 7 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_44520133/article/details/104220800
今日推荐