图片压缩库 - image-compressor

2017-07-25      812      JavaScript
项目简介

image-compressor

A simple JavaScript image compressor. Uses the Browser's native canvas.toBlob API to do the compression work. General use this to precompress a client image file before upload it.

Main

dist/
├── image-compressor.js        (UMD)
├── image-compressor.min.js    (UMD, compressed)
├── image-compressor.common.js (CommonJS, default)
└── image-compressor.esm.js    (ES Module)

Getting started

Installation

  • Download the latest release .
  • Clone the repository:git clone https://github.com/xkeshi/image-compressor.git.
  • Install with NPM :npm install xkeshi/image-compressor --force.

Usage

Syntax

new ImageCompressor([file[, options]])

file

The target image file for compressing.

options

  • Type:Object
  • Optional

The options for compressing. Check out the availableoptions.

Example

<input type="file" id="file" accept="image/*">
import axios from 'axios';
import ImageCompressor from 'image-compressor';

document.getElementById('file').addEventListener('change', (e) => {
  const file = e.target.files[0];

  if (!file) {
    return;
  }

  new ImageCompressor(file, {
    quality: .6,
    success(result) {
      const formData = new FormData();

      formData.append('file', result);

      // 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);
    },
  });
})

⬆ back to top

Options

maxWidth

  • Type:number
  • Default:Infinity

The max width of the output image. The value should be greater then0.

maxHeight

  • Type:number
  • Default:Infinity

The max height of the output image. The value should be greater then0.

minWidth

  • Type:number
  • Default:0

The min width of the output image. The value should be greater then0and should not be greater than themaxWidth.

minHeight

  • Type:number
  • Default:0

The min height of the output image. The value should be greater then0and should not be greater than themaxHeight.

width

  • Type:number
  • Default:undefined

The width of the output image. If not specified, the natural width of the original image will be used, or if theheightoption is set, the width will be computed automatically by the natural aspect ratio.

height

  • Type:number
  • Default:undefined

The height of the output image. If not specified, the natural height of the original image will be used, or if thewidthoption is set, the height will be computed automatically by the natural aspect ratio.

Note:In order to keep the same aspect ratio to the original image, if thewidthoption is set, will use it compute the height automatically, which means theheightoption will be ignored.

quality

  • Type:number
  • Default:0.8

The quality of the output image. It must be a number between0and1. Be careful to use1as it may make the size of the output image become larger. Check out canvas.toBlob for more detail.

Note:This option only available forimage/jpegandimage/webpimages.

Examples(in Chrome 59):

Quality Input size Output size Compression ratio Description
0 2.12 MB 229.56 KB 89.43% -
0.2 2.12 MB 422.82 KB 80.53% -
0.4 2.12 MB 578.25 KB 73.37% -
0.6 2.12 MB 747.85 KB 65.56% Recommend
0.8 2.12 MB 1.18 MB 44.14% Recommend
1 2.12 MB 2.12 MB 0% Not recommend
NaN 2.12 MB 2.05 MB 3.19% -

mimeType

  • Type:string
  • Default:'auto'

The mime type of the output image. By default, the original mime type of the source image file will be used.

convertSize

  • Type:number
  • Default:5000000(5MB)

PNG files over this value will be converted to JPEGs. To disable this, just set the value toInfinity. See #2 .

success(result)

  • Type:Function
  • Default:null
  • Parameters:
    • result: The compressed image (aBlobobject).

The success callback for the image compressing process.

error(err)

  • Type:Function
  • Default:null
  • Parameters:
    • err: The compression error (anErrorobject).

The error callback for the image compressing process.

⬆ back to top

Methods

compress(file[, options])

  • file:
    • Type:FileorBlob
    • The target image file for compressing.
  • options(optional):
    • Type:Object
    • The options for compressing.
  • (return value):
    • Type:Promise

Compress an image file.

const imageCompressor = new ImageCompressor();

imageCompressor.compress(file, options)
  .then((result) => {
    // Handle the compressed image file.
  })
  .catch((err) => {
    // Handle the error
  })

⬆ back to top

Browser support

  • Chrome (latest)
  • Firefox (latest)
  • Safari (latest)
  • Opera (latest)
  • Edge (latest)
  • Internet Explorer 10+ (requiresbabel-polyfillforPromisesupport)