开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第7天,点击查看活动详情
Compressor.js是基于javascript和canvas的图片压缩插件,在github拥有3.6k的star。因为用到canvas,所以不能使用canvas的超低版本浏览器无法兼容,且图片压缩是有损压缩。
Compressor.js提供了一个在线压缩的网站,如果你仅仅只是想要压缩一张图片,可以直接前往 Compressor.js 使用
安装和导入
安装
npm install compressorjs
导入
import Compressor from 'compressorjs';
如果你项目并没有使用npm,可以在github上下载对应的dist文件:Compressor.js的github
使用
new Compressor(file[, options])
options配置
- checkOrientation
{
type: boolean,
default: true
}
是否读取图像的 Exif 方向值,根据这个方向来自动旋转或翻转图像(Exif只存在于JPEG格式图像)。
至于Exif是什么,可以参考这篇文章:Exif图片方向的一些发现
一般情况下不需要理会这个参数,保持默认值就好。
- maxWidth
{
type: number,
default: Infinity
}
压缩后的图片最大宽度,这个值应该大于0。
插件基于canvas,而各大浏览器厂商对canvas的宽高都做了限制,超过这个限制可能会导致程序崩溃,已知限制宽高最小的是IE浏览器,只有4096,建议设置这个参数时,小于4096。 其他尺寸参考:canvas的最大宽高
- maxHeight
{
type: number,
default: Infinity
}
压缩后的图片最大高度,这个值应该大于0。
- minWidth
{
type: number,
default: 0
}
压缩后的图片最小宽度,这个值应该大于0且小于maxWidth。
- minHeight
{
type: number,
default: 0
}
压缩后的图片最小高度,这个值应该大于0且小于maxHeight。
- width
{
type: number
}
压缩后的图片的宽度,如果没有设置width,但设置了height,图像会自动根据height和图像比例来决定图片的宽度。
- height
{
type: number
}
压缩后的图片的高度,如果没有设置height,但设置了width,图像会自动根据width和图像比例来决定图片的宽度。
- resize
{
type: string,
default: 'none',
options: ['none','contain','cover']
}
当图片宽高设置不符合原图比例时,如果填充到新的尺寸中,类似于css属性的object-fit
- mimeType
{
type: string,
default: 'auto'
}
压缩后的图片类型,默认输出原图像的类型
- strict
{
type: boolean,
default: false
}
当压缩图像的大小大于原始图像时,是否直接输出原始图片。如果设置为true,在以下几种情况下会不生效:
- 设置了mimeType参数,且与原始图片的mime类型不同
- 设置了width参数,且比原始图片宽度更大
- 设置了height参数,且比原始图片高度更大
- 设置了minWidth参数,且比原始图片宽度更大
- 设置了minHeight参数,且比原始图片高度更大
- 设置了maxWidth参数,且比原始图片宽度小
- 设置了maxHeight参数,且比原始图片高度小
- quality
{
type: number,
default: 0.8
}
压缩图片的质量,值应该基于0-1之间,该参数只对 jpeg、webp有效,该参数将作用于canvas上,参考 canvas.toBlob()
- drew(context, canvas)
{
type: Function,
default: null
}
压缩后执行的画布操作,可以进行水印等绘制。
- success(result)
{
type: Function,
default: null
}
压缩成功的回调,得到result为Blob对象
- error(err)
{
type: Function,
default: null
}
压缩失败的回调
简单的实现压缩以及保存压缩后的图片
// 压缩
let compressorImage = null // 压缩图片路径
// ... 省略input获取file文件代码
new Compressor(file, {
quality: 0.6,
success: (result) => {
compressorImage = URL.createObjectURL(result);
// 下载压缩后的图片
save(compressorImage,Date.now())
},
error: (err) => {
console.log(err.message);
}
});
function save(url,name) {
let link = document.createElement('a');
link.href = url;
link.download = name;
link.target = "_blank";
link.click();
}
```Compressor.js压缩图片