图片压缩

如题

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)
}

你可能感兴趣的:(图片压缩)