微信小程序图片压缩 wx.createSelectorQuery wx.canvasToTempFilePath


// 1、在 WXML 文件中使用 CSS 把页面上 canvas 隐藏起来
<canvas id="imageCanvas"  style=" position: absolute; left: -999px; top: -999px; z-index: -1;" type="2d" />

// 2、图片压缩方法
zipImage(file) {
    return new Promise((resolve, reject) = > {
        wx.createSelectorQuery().select('#imageCanvas') // 对应 WXML 中填入的 canvas 的 id
        .fields({
            node: true,
            size: true
        }).exec((res) = > {
            // Canvas 对象
            const canvas = res[0].node
            // Canvas 绘制上下文
            const context = canvas.getContext('2d')
            const image = canvas.createImage()
            image.src = file.url
            image.onload = () = > {
                let originWidth = image.width
                let originHeight = image.height
                console.log('原图图片宽高大小', originWidth, originHeight)
                // 最大尺寸限制 
                let maxWidth = 864, maxHeight = 648
                // 目标尺寸
                let targetWidth = originWidth
                let targetHeight = originHeight
                //等比例压缩,如果宽度大于高度,则宽度优先,否则高度优先
                if (originWidth > maxWidth || originHeight > maxHeight) {
                    if (originWidth / originHeight > maxWidth / maxHeight) {
                        targetWidth = maxWidth
                        targetHeight = Math.round(maxWidth * (originHeight / originWidth))
                    } else {
                        targetHeight = maxHeight
                        targetWidth = Math.round(maxHeight * (originWidth / originHeight))
                    }
                }
                canvas.width = targetWidth
                canvas.height = targetHeight
                setTimeout(() = > {
                    console.log('目标图片的宽高大小', targetWidth, targetHeight)
                    context.fillRect(0, 0, targetWidth, targetHeight)
                    context.drawImage(image, 0, 0, targetWidth, targetHeight)
                    wx.canvasToTempFilePath({
                        canvas, quality: 0.5,
                        fileType: 'jpg',
                        width: targetWidth / 2, //canvas的宽高(生成图片的范围)
                        heght: targetHeight / 2,
                        destWidth: (targetWidth / 2) * wx.getWindowInfo().pixelRatio,
                        destHeight: (targetHeight / 2) * wx.getWindowInfo().pixelRatio,
                        success: (res) = > {
                            resolve(res.tempFilePath)
                        },
                        fail: (res) = > {
                            reject()
                        }
                    })
                }, 500)
            }
        })
    })
}

// 3、使用图片压缩
let tempFilePath = null
// 压缩前判断一下 File 的大小 如果小于 1Mb 则不压缩了
if (item.size > 1024 * 1024) {
    tempFilePath = await this.zipImage(item).catch (err = > {
        console.log('文件压缩失败')
    })
}
// upload 为自己封装的上传图片方法
const result = await upload(tempFilePath || item.url).catch ((err) = > {
    console.log(err || '文件上传失败')
})

一些注意事项

  1. Canvas 生成的图片显示不全的话 请设置 canvas.width = targetWidth 和 canvas.height = targetHeight 以及 wx.canvasToTempFilePath 的 width、heght、destWidth、destHeight 参数。
  2. Canvas 显示正常但是导出的图片不正常的话 适当调节 wx.canvasToTempFilePath 外的 setTimeout 的时间。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值