browser-image-compression
Advanced tools
Comparing version 1.0.17 to 2.0.0
@@ -1,5 +0,4 @@ | ||
// Type definitions for browser-image-compression 1.0 | ||
// Type definitions for browser-image-compression 2.0 | ||
// Project: https://github.com/Donaldcwl/browser-image-compression | ||
// Definitions by: Donald <https://github.com/Donaldcwl> & Jamie Haywood <https://github.com/jamiehaywood> | ||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped | ||
@@ -11,3 +10,3 @@ interface Options { | ||
maxWidthOrHeight?: number; | ||
/** @default false */ | ||
/** @default true */ | ||
useWebWorker?: boolean; | ||
@@ -24,2 +23,6 @@ /** @default 10 */ | ||
initialQuality?: number; | ||
/** @default false */ | ||
alwaysKeepResolution?: boolean; | ||
/** @default undefined */ | ||
signal?: AbortSignal; | ||
} | ||
@@ -26,0 +29,0 @@ |
{ | ||
"name": "browser-image-compression", | ||
"version": "1.0.17", | ||
"version": "2.0.0", | ||
"description": "Compress images in the browser", | ||
@@ -42,3 +42,2 @@ "main": "dist/browser-image-compression.js", | ||
"dependencies": { | ||
"core-js": "^3.16.1", | ||
"uzip": "0.20201231.0" | ||
@@ -73,3 +72,4 @@ }, | ||
"rollup-plugin-nodent": "^0.2.2", | ||
"rollup-plugin-terser": "^5.0.0" | ||
"rollup-plugin-terser": "^5.0.0", | ||
"rollup-plugin-visualizer": "^5.6.0" | ||
}, | ||
@@ -76,0 +76,0 @@ "config": { |
229
README.md
@@ -1,2 +0,2 @@ | ||
# Browser Image Compression # | ||
# Browser Image Compression | ||
[![npm](https://img.shields.io/npm/v/browser-image-compression.svg)](https://www.npmjs.com/package/browser-image-compression) | ||
@@ -8,86 +8,21 @@ [![npm](./coverage/badge.svg)](https://github.com/Donaldcwl/browser-image-compression) | ||
## Features ## | ||
- You can use this module to compress jpeg and png image by reducing **resolution** or **storage size** before uploading to application server to save bandwidth. | ||
- **Multi-thread** (web worker) non-blocking compression are supported through options. | ||
## Features | ||
- You can use this module to compress jpeg and png images by reducing **resolution** or **storage size** before uploading to the application server to save bandwidth. | ||
- **Multi-thread** (web worker) non-blocking compression is supported through options. | ||
## Install ## | ||
You can download imageCompression from the [dist folder][dist]. Alternatively, you can install it via yarn or npm | ||
``` | ||
npm install browser-image-compression --save | ||
or | ||
yarn add browser-image-compression | ||
``` | ||
or use a CDN like [delivrjs]: | ||
``` | ||
https://cdn.jsdelivr.net/npm/browser-image-compression@1.0.17/dist/browser-image-compression.js | ||
or | ||
https://cdn.jsdelivr.net/npm/browser-image-compression@latest/dist/browser-image-compression.js | ||
``` | ||
## Support | ||
If this project help you reduce time to develop, you can buy me a cup of coffee :) | ||
## Upgrade to version 2 | ||
Note that core-js is dropped in version 2, please read the [IE support](#ie-support) section. | ||
<a href="https://www.buymeacoffee.com/donaldcwl" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-red.png" alt="Buy Me A Coffee" height=60 width=217 ></a> | ||
## Demo / Example | ||
open https://donaldcwl.github.io/browser-image-compression/example/basic.html | ||
## How to use this module in your project? ## | ||
#### Use as ES module #### | ||
or check the "[example]" folder in this repo | ||
(can be used in framework like React, Angular, Vue etc) | ||
(work with bundler like webpack and rollup) | ||
```javascript | ||
import imageCompression from 'browser-image-compression'; | ||
``` | ||
or | ||
#### In html file #### | ||
## Usage | ||
```html | ||
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/browser-image-compression@1.0.17/dist/browser-image-compression.js"></script> | ||
``` | ||
## API ## | ||
### Main function ### | ||
```javascript | ||
// you should provide one of maxSizeMB, maxWidthOrHeight in the options | ||
const options: Options = { | ||
maxSizeMB: number, // (default: Number.POSITIVE_INFINITY) | ||
maxWidthOrHeight: number, // compressedFile will scale down by ratio to a point that width or height is smaller than maxWidthOrHeight (default: undefined) | ||
// but, automatically reduce the size to smaller than the maximum Canvas size supported by each browser. | ||
// Please check the Caveat part for details. | ||
onProgress: Function, // optional, a function takes one progress argument (percentage from 0 to 100) | ||
useWebWorker: boolean, // optional, use multi-thread web worker, fallback to run in main-thread (default: true) | ||
// following options are for advanced users | ||
maxIteration: number, // optional, max number of iteration to compress the image (default: 10) | ||
exifOrientation: number, // optional, see https://stackoverflow.com/a/32490603/10395024 | ||
fileType: string, // optional, fileType override | ||
initialQuality: number // optional, initial quality value between 0 and 1 (default: 1) | ||
} | ||
imageCompression(file: File, options: Options): Promise<File> | ||
``` | ||
#### Caveat #### | ||
Each browser limits [the maximum size](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas#maximum_canvas_size) of a Canvas object. <br/> | ||
So, we resize the image to less than the maximum size that each browser restricts. <br/> | ||
(However, the `proportion/ratio` of the image remains.) | ||
### Helper function ### | ||
- for advanced users only, most users won't need to use the helper functions | ||
```javascript | ||
imageCompression.getDataUrlFromFile(file: File): Promise<base64 encoded string> | ||
imageCompression.getFilefromDataUrl(dataUrl: string, filename: string, lastModified?: number): Promise<File> | ||
imageCompression.loadImage(url: string): Promise<HTMLImageElement> | ||
imageCompression.drawImageInCanvas(img: HTMLImageElement, fileType?: string): HTMLCanvasElement | OffscreenCanvas | ||
imageCompression.drawFileInCanvas(file: File, options?: Options): Promise<[ImageBitmap | HTMLImageElement, HTMLCanvasElement | OffscreenCanvas]> | ||
imageCompression.canvasToFile(canvas: HTMLCanvasElement | OffscreenCanvas, fileType: string, fileName: string, fileLastModified: number, quality?: number): Promise<File> | ||
imageCompression.getExifOrientation(file: File): Promise<number> // based on https://stackoverflow.com/a/32490603/10395024 | ||
``` | ||
## Usage ## | ||
```html | ||
<input type="file" accept="image/*" onchange="handleImageUpload(event);"> | ||
``` | ||
async await syntax: | ||
### async await syntax: | ||
```javascript | ||
@@ -117,32 +52,131 @@ async function handleImageUpload(event) { | ||
``` | ||
Promise.then().catch() syntax: | ||
### Promise.then().catch() syntax: | ||
<details> | ||
<summary>Click to expand</summary> | ||
```javascript | ||
function handleImageUpload(event) { | ||
var imageFile = event.target.files[0]; | ||
console.log('originalFile instanceof Blob', imageFile instanceof Blob); // true | ||
console.log(`originalFile size ${imageFile.size / 1024 / 1024} MB`); | ||
var options = { | ||
maxSizeMB: 1, | ||
maxWidthOrHeight: 1920, | ||
useWebWorker: true | ||
} | ||
imageCompression(imageFile, options) | ||
.then(function (compressedFile) { | ||
console.log('compressedFile instanceof Blob', compressedFile instanceof Blob); // true | ||
console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeMB | ||
return uploadToServer(compressedFile); // write your own logic | ||
}) | ||
.catch(function (error) { | ||
console.log(error.message); | ||
}); | ||
} | ||
``` | ||
</details> | ||
## Installing | ||
### Use as ES module: | ||
You can install it via npm or yarn | ||
```bash | ||
npm install browser-image-compression --save | ||
# or | ||
yarn add browser-image-compression | ||
``` | ||
```javascript | ||
import imageCompression from 'browser-image-compression'; | ||
``` | ||
(can be used in frameworks like React, Angular, Vue etc) | ||
(work with bundlers like webpack and rollup) | ||
### (or) Load UMD js file: | ||
You can download imageCompression from the [dist folder][dist]. | ||
Alternatively, you can use a CDN like [delivrjs]: | ||
```html | ||
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/browser-image-compression@2.0.0/dist/browser-image-compression.js"></script> | ||
``` | ||
## Support | ||
If this project helps you reduce the time to develop, you can buy me a cup of coffee :) | ||
<a href="https://donaldcwl.github.io/donation/" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-red.png" alt="Buy Me A Coffee" height=60 width=217 ></a> | ||
## API | ||
### Main function | ||
```javascript | ||
// you should provide one of maxSizeMB, maxWidthOrHeight in the options | ||
const options: Options = { | ||
maxSizeMB: number, // (default: Number.POSITIVE_INFINITY) | ||
maxWidthOrHeight: number, // compressedFile will scale down by ratio to a point that width or height is smaller than maxWidthOrHeight (default: undefined) | ||
// but, automatically reduce the size to smaller than the maximum Canvas size supported by each browser. | ||
// Please check the Caveat part for details. | ||
onProgress: Function, // optional, a function takes one progress argument (percentage from 0 to 100) | ||
useWebWorker: boolean, // optional, use multi-thread web worker, fallback to run in main-thread (default: true) | ||
signal: AbortSignal, // options, to abort / cancel the compression | ||
// following options are for advanced users | ||
maxIteration: number, // optional, max number of iteration to compress the image (default: 10) | ||
exifOrientation: number, // optional, see https://stackoverflow.com/a/32490603/10395024 | ||
fileType: string, // optional, fileType override e.g., 'image/jpeg', 'image/png' (default: file.type) | ||
initialQuality: number, // optional, initial quality value between 0 and 1 (default: 1) | ||
alwaysKeepResolution: boolean // optional, only reduce quality, always keep width and height (default: false) | ||
} | ||
imageCompression(file: File, options: Options): Promise<File> | ||
``` | ||
#### Caveat | ||
Each browser limits [the maximum size](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas#maximum_canvas_size) of a Canvas object. <br/> | ||
So, we resize the image to less than the maximum size that each browser restricts. <br/> | ||
(However, the `proportion/ratio` of the image remains.) | ||
#### Abort / Cancel Compression | ||
To use this feature, please check the browser compatibility: https://caniuse.com/?search=AbortController | ||
```javascript | ||
function handleImageUpload(event) { | ||
var imageFile = event.target.files[0]; | ||
console.log('originalFile instanceof Blob', imageFile instanceof Blob); // true | ||
console.log(`originalFile size ${imageFile.size / 1024 / 1024} MB`); | ||
var controller = new AbortController(); | ||
var options = { | ||
maxSizeMB: 1, | ||
maxWidthOrHeight: 1920, | ||
useWebWorker: true | ||
// other options here | ||
signal: controller.signal, | ||
} | ||
imageCompression(imageFile, options) | ||
.then(function (compressedFile) { | ||
console.log('compressedFile instanceof Blob', compressedFile instanceof Blob); // true | ||
console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeMB | ||
return uploadToServer(compressedFile); // write your own logic | ||
}) | ||
.catch(function (error) { | ||
console.log(error.message); | ||
console.log(error.message); // output: I just want to stop | ||
}); | ||
// simulate abort the compression after 1.5 seconds | ||
setTimeout(function () { | ||
controller.abort(new Error('I just want to stop')); | ||
}, 1500); | ||
} | ||
``` | ||
## Demo / Example ## | ||
open https://donaldcwl.github.io/browser-image-compression/example/basic.html | ||
### Helper function | ||
- for advanced users only, most users won't need to use the helper functions | ||
```javascript | ||
imageCompression.getDataUrlFromFile(file: File): Promise<base64 encoded string> | ||
imageCompression.getFilefromDataUrl(dataUrl: string, filename: string, lastModified?: number): Promise<File> | ||
imageCompression.loadImage(url: string): Promise<HTMLImageElement> | ||
imageCompression.drawImageInCanvas(img: HTMLImageElement, fileType?: string): HTMLCanvasElement | OffscreenCanvas | ||
imageCompression.drawFileInCanvas(file: File, options?: Options): Promise<[ImageBitmap | HTMLImageElement, HTMLCanvasElement | OffscreenCanvas]> | ||
imageCompression.canvasToFile(canvas: HTMLCanvasElement | OffscreenCanvas, fileType: string, fileName: string, fileLastModified: number, quality?: number): Promise<File> | ||
imageCompression.getExifOrientation(file: File): Promise<number> // based on https://stackoverflow.com/a/32490603/10395024 | ||
``` | ||
or check the "[example]" folder in this repo | ||
@@ -155,9 +189,20 @@ ## Browsers support | ||
### IE support | ||
This library uses ES features such as Promise API, globalThis. If you need to support browsers that do not support new ES features like IE. You can include the core-js polyfill in your project. | ||
You can include the following script to load the core-js polyfill: | ||
```html | ||
<script src="https://cdnjs.cloudflare.com/ajax/libs/core-js/3.21.1/minified.min.js"></script> | ||
``` | ||
## Remarks for compression to work in Web Worker | ||
The browser need to support "OffscreenCanvas" API in order to take advantage of non-blocking compression. If browser do not support "OffscreenCanvas" API, main thread is used instead. See https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas#browser_compatibility for browser compatibility of "OffscreenCanvas" API. | ||
The browser needs to support "OffscreenCanvas" API in order to take advantage of non-blocking compression. If the browser does not support "OffscreenCanvas" API, the main thread is used instead. See https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas#browser_compatibility for browser compatibility of "OffscreenCanvas" API. | ||
## Typescript type definitions ## | ||
## Typescript type definitions | ||
Typescript definitions are included in the package & referenced in the `types` section of the `package.json` | ||
## Contribution ## | ||
## Contribution | ||
1. fork the repo and git clone it | ||
@@ -164,0 +209,0 @@ 2. run `npm run watch` # it will watch code change in lib/ folder and generate js in dist/ folder |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
1
217
451093
28
8
594
- Removedcore-js@^3.16.1
- Removedcore-js@3.40.0(transitive)