前端的图片压缩image-compressor(可在图片上传前实现图片压缩)

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 属性</

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值