前端js对图片进行尺寸及质量压缩处理

function:

/**
 * 图片尺寸及质量压缩
 * @param file 图片文件
 * @param maxWidth 最大宽度,若图片超过此宽度则缩放到此宽度,同时高度进行等比例缩放
 * @param quality 质量,0-1之间的值
 * @returns 带着压缩处理后的base64数据的Promise对象
 */
function scaleImage(file, maxWidth = 800, quality) {
    return new Promise(function (resolve, reject) {
        let fileType = file.type
        let scaledBase64Data = ''
        let reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = function () {
            let img = new Image()
            const originBase64Data = this.result
            img.src = originBase64Data // 文件base64数据
            img.onload = function () { //图片加载完后
                console.log('image width:', img.width)
                console.log('image height:', img.height)
                let scaleWidth = img.width
                let scaleHeight = img.height
                if (img.width > maxWidth) {
                    console.log('图片超大,进行尺寸缩小处理')
                    scaleWidth = maxWidth
                    scaleHeight = img.height * ( maxWidth / img.width )
                    console.log('image scaleWidth:', scaleWidth)
                    console.log('image scaleHeight:', scaleHeight)
                    const canvas = document.createElement("canvas");
                    const context = canvas.getContext("2d");
                    canvas.width = scaleWidth;
                    canvas.height = scaleHeight;
                    context.drawImage(img, 0, 0, scaleWidth, scaleHeight);
                    scaledBase64Data = canvas.toDataURL(fileType, quality)
                    console.log('scaledBase64Data', scaledBase64Data)
                    resolve(scaledBase64Data)
                } else {
                    resolve(originBase64Data)
                }
            }
        }
        reader.onerror = function (error) {
            reject(error)
        }
    })
}

用法:

scaleImage(file, 800, 1).then((base64) => {
    console.log('scaledBase64Data:', base64)
    document.getElementById('myImage').src = base64
})

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值