大家好,我是「前端实验室」
爱分享的了不起~
想必大家都用过图片压缩工具吧!对于前端来说这图片压缩是必不可少的,今天就给大家介绍一个js工具库,让前端也能实现图片压缩~
js-image-compressor
是一个实现轻量级图片压缩的 javascript 库,压缩后仅有 5kb,在前端页面即可实现对图片的压缩。在提供基本图片压缩功能同时,还暴露出图片处理相关公用方法
npm安装
npm install js-image-compressor --save-dev
简单配置
import ImageCompressor from 'js-image-compressor';
function imageCompress(file: any) {
const size = file.size / 1024
return new Promise((resolve, reject) => {
const options = {
file: file,
quality: 0.8, // 图片质量
mimeType: 'image/jpeg',
maxWidth: file.height,
maxHeight: file.width,
minWidth: 10, // 指定压缩图片最小宽度
width: 1080, // 指定压缩图片宽度
convertSize: Infinity,
loose: true,
redressOrientation: true,
success: (result) => {
resolve(result)
},
error: (msg) => {
reject(msg)
},
}
new ImageCompressor(options)
})
}
其中,钩子函数 beforeCompress 发生在读取图片之后,创建画布之前;钩子函数 success 函数发生在压缩完成生成图片之后。它们回调参数 result 是整合来尺寸、图片类型和大小等相关信息的 blob 对象。
输出的压缩图片符合以下特征:
在压缩输出图片之前,我们还可以对画布进行一些自定义处理,融入元素。
var options = {
file: file,
// 图片绘画前
beforeDraw: function (ctx) {
vm.btnText = '准备绘图...';
console.log('准备绘图...');
ctx.filter = 'grayscale(100%)';
},
// 图片绘画后
afterDraw: function (ctx, canvas) {
ctx.restore();
vm.btnText = '绘图完成...';
console.log('绘图完成...');
ctx.fillStyle = '#fff';
ctx.font = (canvas.width * 0.1) + 'px microsoft yahei';
ctx.fillText(vm.watermarkText, 10, canvas.height - 20);
},
};
new ImageCompressor(options);
beforeDraw 是在画布创建后,图片绘画前的钩子函数,afterDraw 是在图绘画后的钩子函数。
这里有张图归纳了从本地上传到对图片压缩的详细过程
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有