Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现 base64图片的压缩? #15

Open
JslinSir opened this issue Jun 13, 2022 · 0 comments
Open

实现 base64图片的压缩? #15

JslinSir opened this issue Jun 13, 2022 · 0 comments
Labels
奇巧淫技 开发中遇到的一些奇巧淫技

Comments

@JslinSir
Copy link
Owner

原理

通过 cavas的方式 把图片进行压缩

/**
 * 压缩base64 图片
 * @param {*} quality  压缩系数0-1之间
 */
export const compressBase64Img = ({quality=0.6,base64Img}) => {
    return new Promise((revose,reject)=>{
        const newImage = new Image()
        newImage.src = base64Img
        newImage.setAttribute("crossOrigin", 'Anonymous')
        newImage.onload = function () {
            const canvas = document.createElement('canvas')
            const ctx = canvas.getContext("2d")
            canvas.width = this.width
            canvas.height = this.height
            ctx.clearRect(0, 0, canvas.width, canvas.height)
            ctx.drawImage(this, 0, 0, canvas.width, canvas.height)
            const newBase64 = canvas.toDataURL("image/jpeg", quality)
            revose(newBase64) 
        }
        newImage.onerror = function () {
            reject('图片加载出错')
        }

    })
  
 
}
@JslinSir JslinSir added the 奇巧淫技 开发中遇到的一些奇巧淫技 label Jun 24, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
奇巧淫技 开发中遇到的一些奇巧淫技
Projects
None yet
Development

No branches or pull requests

1 participant