圖片壓縮

export function CompressPictures(file, quality = 0.2) {
    return new Promise((resolve) => {
        const reader = new FileReader() // 創(chuàng)建 FileReader
        reader.onload = ({
            target: {
                result: src
            }
        }) => {
            const image = new Image() // 創(chuàng)建 img 元素
            image.onload = async() => {
                const canvas = document.createElement('canvas') // 創(chuàng)建 canvas 元素
                canvas.width = image.width
                canvas.height = image.height
                canvas.getContext('2d').drawImage(image, 0, 0, image.width, image.height) // 繪制 canvas
                const canvasURL = canvas.toDataURL('image/jpeg', quality)
                const buffer = atob(canvasURL.split(',')[1])
                let length = buffer.length
                const bufferArray = new Uint8Array(new ArrayBuffer(length))
                while(length--) {
                    bufferArray[length] = buffer.charCodeAt(length)
                }
                const miniFile = new File([bufferArray], file.name, {
                    type: 'image/jpeg'
                })
                resolve({
                    file: miniFile,
                    origin: file,
                    beforeSrc: src,
                    afterSrc: canvasURL,
                    beforeKB: Number((file.size / 1024).toFixed(2)),
                    afterKB: Number((miniFile.size / 1024).toFixed(2))
                })
            }
            image.src = src
        }
        reader.readAsDataURL(file)
    })
}

使用示例

        // 開挖前圖片
        async beforeImgHandleChange(file) {
            const isIMG = ["image/jpeg", "image/jpg", "image/png"].includes(file.raw.type)
            const isLt1M = file.size / 1024 / 1024 < 10
            if (isIMG && isLt1M) {
                let res = await CompressPictures(file.raw, 0.2)
                let base64 = await this.getBase64(res.file)
                this.beforeExcavationImgUrl = base64
                this.form.beforeExcavationImgUrl = res.file
            } else {
                this.$message.warning('只能上傳jpg跟jpeg類型圖片,且大小不超過10M')
                return
            }
        },

引用自https://blog.csdn.net/u013938578/article/details/128762512

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容