uniapp js上传图片压缩

export default async function imgCompress(fileObj,quality) {
    return new Promise((resolve, reject) => {
        try {
            const image = new Image()
            image.src = URL.createObjectURL(fileObj)
            image.onload = function() {
                const that = this
                // 默认按比例压缩
                let w = that.width
                let h = that.height
                const scale = w / h
                w = fileObj.width || w
                h = fileObj.height || (w / scale)
                
                // 生成canvas
                const canvas = document.createElement('canvas')
                const ctx = canvas.getContext('2d')
                // 创建属性节点
                const anw = document.createAttribute('width')
                anw.nodeValue = w
                const anh = document.createAttribute('height')
                anh.nodeValue = h
                canvas.setAttributeNode(anw)
                canvas.setAttributeNode(anh)
                ctx.drawImage(that, 0, 0, w, h)
                
                // quality值越小,所绘制出的图像越模糊
                const data = canvas.toDataURL('image/jpeg', quality)
                // 压缩完成执行回调
                const newFile = base64toFile(data)
                resolve(newFile)
            }
        } catch (e) {}
    })
}
function base64toFile(base, filename) {
    var arr = base.split(',');
    var mime = arr[0].match(/:(.*?);/)[1];
    var suffix = mime.split("/")[1];
    var bstr = atob(arr[1]);
    var n = bstr.length;
    var u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    //转换成file对象
    return new File([u8arr], `filename.${suffix}`, {
        type: mime
    });
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容