image-compressor
一个简单的JavaScript图像压缩器。使用浏览器的原生canvas.toBlob API做的压缩工作。一般使用此压缩是在客户端图像文件上传之前。
实例模板:Website
github:image-compressor
Getting started(新手入门)
Install(npm 安装)
npm install image-compressor.js // 注意是image-compressor.js 不是 image-compressor那是另一个包
Usage(使用)
Syntax语法
new ImageCompressor([file[, options]])
参数说明
file:(可选)压缩的目标图像文件,类型是 File 或者 Blob
options:(可选)压缩选项,类型是 Object
案例
<input type="file" id="file" accept="image/*">
import axios from 'axios'
import ImageCompressor from 'image-compressor.js' // 引入
document.getElementById('file').addEventListener('change', (e) => {
const file = e.target.files[0]; // file对象
if (!file) {
return } // 为空处理
new ImageCompressor(file, {
quality: .6,
success(result) {
const formData = new FormData(); // FormData学习地址 https://developer.mozilla.org/zh-CN/docs/Web/API/FormData
formData.append('file', result, result.name);
// 通过XMLHttpRequest服务发送压缩的图像文件-Send the compressed image file to server with XMLHttpRequest.
axios.post('/path/to/upload', formData).then(() => {
console.log('Upload success');
});
},
error(e) {
console.log(e.message);
},
});
});
Options参数
checkOrientation
是否检查图片的 orientation 属性,类型是 boolean。默认值是 true。
提示:如果读取图像的EXIF的 orientation 属性(JPEG图像),有可能根据 orientation 属性自动翻转或旋转图像。
注意:不要一直相信这一点,因为一些JPEG图像有不正确的(不是标准的) orientation 属性</