关于javascript:图片压缩

32次阅读

共计 998 个字符,预计需要花费 3 分钟才能阅读完成。

如题

const compressImage = async (file, quality=.9) => {
    // file 文件对象
    // quailty  压缩比
    
    let img = new Image(),
        reader = new FileReader(),
        canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d')
    
    reader.readAsDataURL(file)
    reader.onload = function(e){img.src = e.target.result}
    
    return new Promise((resolve, reject)=>{img.onload = function(){
            let _ = this,
                w = _.width,
                h = _.height,
                scale = w / h,
                anw = document.createAttribute('width'),
                anh = document.createAttribute('height')
                
            anw.nodeValue = w
            anh.nodeValue = h
            canvas.setAttribute(anw)
            canvas.setAttribute(anh)
            // 在 canvas 绘制前填充红色背景
            ctx.rect(0, 0, w, h)
            ctx.fillStyle = 'white'
            ctx.fill()
            ctx.drawImage(_, 0, 0, w, h)

            let src = canvas.toDataURL('image/jpeg', quality) //quality 在 'image/jpeg' 时才起作用
            
            // base64 转 file
            let arr = src.split(','),
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(8)
                while(n--){u8arr[n] = bstr.charCodeAt(n)
                }
            
            let newFile = new File([u8arr], file.name, {type: file.type})
            console.log('压缩后的图片体积',newFile.size/1024/1024)
            resolve(newFile)
        }
    
    })
    
}

里面调用

const egFunc = async (file)=>{
    const quality = .5
    file = await compressImage(file, quality)
}

正文完
 0