el-upload实现上传图片前将白底图转换为透明图

在beforeUpload时调用

 commonReSize(file, format) {
     return new Promise((resolve, reject) => {
         const that = this
         const img = new Image()
         img.src = URL.createObjectURL(file)
         img.onload = function() {
         let w = img.width
         let h = img.height
         let bl
         if (h > w) {
             bl = (7800 / h).toFixed(1)
         } else {
             bl = (7800 / w).toFixed(1)
         }
         w = w / 10 * bl
         h = h / 10 * bl
         const x = parseInt((800 - w) / 2)
         const y = parseInt((800 - h) / 2)
         const canvas = document.createElement('canvas')
         canvas.width = 800
         canvas.height = 800
         const ctx = canvas.getContext('2d')

         // 将背景颜色设置为白色
         ctx.fillStyle = '#fff'
         ctx.fillRect(0, 0, 800, 800)

         ctx.drawImage(img, x, y, w, h)
             const imageData = ctx.getImageData(0, 0, 800, 800)
             const data = imageData.data
             for (let i = 0; i < data.length; i += 4) {
                 const r = data[i]
                 const g = data[i + 1]
                 const b = data[i + 2]
                 if ([r, g, b].every(v => v < 256 && v > 250)) data[i + 3] = 0
             }
             ctx.putImageData(imageData, 0, 0)
             const compressData = canvas.toDataURL('image/png', 1)
             const blobImg = that.changePicSize(compressData)
             const fs = new File([blobImg], file.name, {
                 type: 'image/png'
             })
             const isLt2M = fs.size / 1024 / 1024 > 3
             if (isLt2M) {
                 this.$message.error('修改图片后图片大小超出3MB的限制,请手动调整尺寸并压缩图片大小!')
                 reject()
             } else {
                 resolve(fs)
             }
         }
     })
 },
 changePicSize(data) {
     let byteString
     if (data.split(',')[0].indexOf('base64') >= 0) {
         byteString = atob(data.split(',')[1])
     } else {
         byteString = unescape(data.split(',')[1])
     }
     const mimeString = data
         .split(',')[0]
         .split(':')[1]
         .split(';')[0]
     const ia = new Uint8Array(byteString.length)
     for (let i = 0; i < byteString.length; i += 1) {
         ia[i] = byteString.charCodeAt(i)
     }
     return new Blob([ia], { type: mimeString })
 },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值