JavaScrip实现图片压缩与分辨率等比例缩放

教程下载地址: 网赚博客https://www.piaodoo.com/创业项目排行榜前十名https://www.piaodoo.com/


实现代码

<input type="file" id="file" />
<script>
    function imageScale(width, originWidth, originHeight) {
        const scaleRatio = width / originWidth;
        const scaleHeight = scaleRatio * originHeight;
        return [width, scaleHeight];
    }
function compress(file, scaleWidth, quality = 0.5) {
    return new Promise((resolve, reject) =&gt; {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (e) =&gt; {
            let img = new Image();
            img.src = e.target.result;
            img.onload = function () {
                // 等比例缩放图片
                const [width, height] = imageScale(
                    scaleWidth,
                    img.width,
                    img.height
                );
                let canvas = document.createElement("canvas");
                img.width = canvas.width = width;
                img.height = canvas.height = height;
                let ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0, img.width, img.height);
                canvas.toBlob(
                    (blob) =&gt; {
                        resolve(blob);
                    },
                    "image/jpeg",
                    quality
                );
            };

            img.onerror = function () {
                reject();
            };
        };
    });
}

file.onchange = function () {
    compress(this.files[0], 200).then((blob) =&gt; {
        let url = window.URL.createObjectURL(blob);
        const img = document.createElement("img");
        img.src = url;
        img.width = 200;
        document.body.appendChild(img);
    });
};

</script>

效果图

方法补充

除了上文的方法,小编还为大家介绍了其他JavaScrip等比压缩图片的方法,希望对大家有所帮助

JS利用Canvas实现图片等比例裁剪、压缩

原理:

图像压缩有两种方式,目前写的方法是两者都支持且能够共同处理

1.图像尺寸裁剪,由大变小

2.尺寸不变,图片质量缩减

引用代码:

if (!HTMLCanvasElement.prototype.toBlob) {
  Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
    value: function(callback, type, quality) {
      var canvas = this
      setTimeout(() => {
        var binStr = atob(canvas.toDataURL(type, quality).split(',')[1])
        var len = binStr.length
        var arr = new Uint8Array(len)
        for (var i = 0; i < len; i++) {
          arr[i] = binStr.charCodeAt(i)
        }
        callback(new Blob([arr], { type: type || 'image/png' }))
      })
    }
  })
}

/**

  • 图片压缩
  • @param {object} options 参数
  • @param {string} options.content 图像内容
  • @param {number} options.maxWidth 最大宽度
  • @param {number} options.maxHeight 最大高度
  • @param {number} options.quality 图像质量
  • @example rotateImage({ content: Img, maxWidth: 1000, maxHeight: 1000, quality: 0.8 })
  • @returns {Promise<object>} 结果值
    */
    const compressionImage = function(options = {}) {
    if (!options || typeof options !== ‘object’) {
    throw new Error([compressionImage error]: options is not a object)
    }
    if (!options.content || (typeof options.content !== ‘string’ && !(options.content instanceof File))) {
    throw new Error([compressionImage error]: options.content is not a string or file)
    }
    if (typeof options.maxWidth !== ‘number’) {
    throw new Error([compressionImage error]: options.maxWidth is not a number)
    }
    if (typeof options.maxHeight !== ‘number’) {
    throw new Error([compressionImage error]: options.maxHeight is not a number)
    }
    if (typeof options.quality !== ‘number’) {
    throw new Error([compressionImage error]: options.quality is not a number)
    }
    return new Promise(resolve => {
    const set = (content, type) => {
    const canvasDOM = document.createElement(‘canvas’)
    const canvasContext = canvasDOM.getContext(‘2d’)
    const img = new Image()
    img.src = content
    img.onload = () => {
    let targetWidth
    let targetHeight
    if (img.width > options.maxWidth && img.height > options.maxHeight) {
    const rate = Math.min(options.maxWidth / img.width, options.maxHeight / img.height)
    targetWidth = img.width * rate
    targetHeight = img.height * rate
    } else if (img.width > options.maxWidth) {
    targetWidth = options.maxWidth
    targetHeight = (options.maxWidth / img.width) * img.height
    } else if (img.height > options.maxHeight) {
    targetHeight = options.maxHeight
    targetWidth = (options.maxHeight / img.height) * img.width
    } else {
    targetWidth = img.width
    targetHeight = img.height
    }
    canvasDOM.width = targetWidth
    canvasDOM.height = targetHeight
    canvasContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, targetWidth, targetHeight)
    const url = canvasDOM.toDataURL(type, options.quality)
    const callback = blob => {
    resolve({ url, blob })
    }
    canvasDOM.toBlob(callback, type, options.quality)
    }
    }
    if (options.content instanceof File) {
    const fileReader = new FileReader()
    fileReader.readAsDataURL(options.content)
    fileReader.onload = e => {
    set(e.target.result, options.content.type)
    }
    } else if (typeof options.content === ‘string’) {
    const fileContent = options.content.includes(‘base64,’) ? options.content : data:image/jpeg;base64,${options.content}
    const fileType =
    options.content.includes(‘data:image/png;base64,’) ? ‘image/png’
    : options.content.includes(‘data:image/gif;base64,’) ? ‘image/gif’ : ‘image/jpeg’
    set(fileContent, fileType)
    }
    })
    }

调用方式:

const { url, blob } = await compressionImage({
  content: 'base64', //图像base64或file文件
  maxWidth: 1000, //最大宽度
  maxHeight: 600, //最大高度
  quality: 0.7 //图像质量,1为100%,建议选值0.95以下,1输出后的图像较大
})
console.log('压缩后的base64内容', url)
console.log('压缩后的blob文件', blob)

到此这篇关于JavaScrip实现图片压缩与分辨率等比例缩放的文章就介绍到这了,更多相关JavaScrip图片等比缩放内容请搜索网赚博客https://www.piaodoo.com/以前的文章或继续浏览下面的相关文章希望大家以后多多支持网赚博客https://www.piaodoo.com/!

                        友情连接:  

茂名一技http://www.szsyby.net/


茂名一技http://www.enechn.com/


美文集http://www.tpyjn.cn/


手游排行前十名http://www.bjkhrx.com/


蔚来汽车http://www.weilaiqiche.cn/

  • 22
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值