1.2.4 • Published 4 years ago

picture-compressor-plus v1.2.4

Weekly downloads
1
License
ISC
Repository
github
Last release
4 years ago

picture-compressor-plus

前端图片压缩工具,使用 canvas 对图片做压缩处理。

使用时,可以设置目标图片的宽高 返回的目标图片填充模式有两种

  • scale 默认等比例缩放,保证图片在设置的宽高之内完成显示,设置宽/高为 0 时则此边为等比自动缩放值

npm.io

  • fill 平铺显示,将图片尺寸设置为参数宽高,可能引起图片变形

npm.io

自动处理图片旋转

依赖 exif-js 库

安装

npm install picture-compressor-plus --save

使用

<template>
  <div id="app">
    <input ref="upload" type="file" value="上传" @change="fileUpload" />
  </div>
</template>
<script>
  import pictureCompressPlus from 'picture-compressor-plus';
  export default {
    name: 'APP',
    methods: {
      fileUpload: function() {
        var file = this.$refs['upload'].files[0];
        var reads = new FileReader();
        reads.readAsDataURL(file);
        reads.onload = function() {
          pictureCompressPlus({
            img: this.result,
            width: 400,
            height: 400,
            fit: 'fill',
          }).then(res => {
            var img = new Image();
            img.src = res.img;
            document.body.appendChild(img);
          });
        };
      },
    },
  };
</script>

or

<input type="file" id="file" />
<script src="../dist/picture-compressor-plus.js"></script>
<script>
  var files = document.getElementById('file');
  files.addEventListener('change', () => {
    var file = files.files[0];
    var reads = new FileReader();
    reads.readAsDataURL(file);
    reads.onload = function() {
      pictureCompressPlus({
        img: this.result,
        width: 1000,
        height: 0,
      }).then(res => {
        var img = new Image();
        img.src = res.img;
        document.body.appendChild(img);
      });
    };
  });
</script>

options 选项

nametype描述是否必选默认值
imgString图片资源的 url 或者 base64Y-
widthNumber生成图片的宽度 >= 0Y-
heightNumber生成图片的高度 >= 0Y-
qualityNumber生产图片质量N0.92
typeString生成图片类型(jpg or png)Njpg
fitString图片填充方式(scale:等比缩放 or fill:填充)Nscale

returns 返回值

nametype描述
imgString图片 base64
widthNumber图片宽度
heightNumber图片高度

Fork from

https://github.com/shb190802/picture-compressor