Browser Image Compression

Image compression in web browser
Alternatives To Browser Image Compression
Project NameStarsDownloadsRepos Using ThisPackages Using ThisMost Recent CommitTotal ReleasesLatest ReleaseOpen IssuesLicenseLanguage
Squoosh19,83752a month ago12January 03, 2023202apache-2.0TypeScript
Make images smaller using best-in-class codecs, right in the browser.
9 days ago4March 22, 2021137Kotlin
An android image compression library.
a year ago9otherPython
Insane(ly slow but wicked good) PNG image optimization
3 years ago57apache-2.0C
an image compression framework.(一个高保真、高压缩比的图片压缩框架)
Caesium Image Compressor1,928
13 days ago28gpl-3.0C++
Caesium is an image compression software that helps you store, send and share digital pictures, supporting JPG, PNG and WebP formats. You can quickly reduce the file size (and resolution, if you want) by preserving the overall quality of the image.
Image Actions1,348
a month ago28gpl-3.0TypeScript
A Github Action that automatically compresses JPEGs, PNGs and WebPs in Pull Requests.
4 years ago26apache-2.0Java
An Advanced Compress Image Library for Android / 高效、简洁的图片压缩工具库
Browser Image Compression97323952 months ago23March 06, 202341mitJavaScript
Image compression in web browser
3 years ago7mitJavaScript
Simple image compression full website code written in node, react and next.js framework. Easy to deploy as a microservice.
2 years ago8mitPython
PyTorch Implementation of "Lossless Image Compression through Super-Resolution"
Alternatives To Browser Image Compression
Select To Compare

Alternative Project Comparisons

Browser Image Compression

npm npm npm

Javascript module to be run in the web browser for image compression.


  • You can use this module to compress jpeg, png, webp, and bmp 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.

Demo / Example


or check the "example" folder in this repo


<input type="file" accept="image/*" onchange="handleImageUpload(event);">

async await syntax:

async function handleImageUpload(event) {

  const imageFile =[0];
  console.log('originalFile instanceof Blob', imageFile instanceof Blob); // true
  console.log(`originalFile size ${imageFile.size / 1024 / 1024} MB`);

  const options = {
    maxSizeMB: 1,
    maxWidthOrHeight: 1920,
    useWebWorker: true,
  try {
    const compressedFile = await imageCompression(imageFile, options);
    console.log('compressedFile instanceof Blob', compressedFile instanceof Blob); // true
    console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeMB

    await uploadToServer(compressedFile); // write your own logic
  } catch (error) {


Promise.then().catch() syntax:

Click to expand
function handleImageUpload(event) {

  var imageFile =[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) {


Use as ES module:

You can install it via npm or yarn

npm install browser-image-compression --save
# or
yarn add browser-image-compression
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.

Alternatively, you can use a CDN like delivrjs:

<script type="text/javascript" src="[email protected]/dist/browser-image-compression.js"></script>


If this project helps you reduce the time to develop, you can buy me a cup of coffee :)

Buy Me A Coffee

(powered by Stripe)


Main function

// 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)
  libURL: string,               // optional, the libURL of this library for importing script in Web Worker (default:
  preserveExif: boolean,        // optional, use preserve Exif metadata for JPEG image e.g., Camera model, Focal length, etc (default: false)

  signal: AbortSignal,          // optional, 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
  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>


Each browser limits the maximum size of a browser Canvas object.
So, we resize the image to less than the maximum size that each browser restricts.
(However, the proportion/ratio of the image remains.)

Abort / Cancel Compression

To use this feature, please check the browser compatibility:

function handleImageUpload(event) {

  var imageFile =[0];

  var controller = new AbortController();

  var options = {
    // other options here
    signal: controller.signal,
  imageCompression(imageFile, options)
    .then(function (compressedFile) {
      return uploadToServer(compressedFile); // write your own logic
    .catch(function (error) {
      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);

Helper function

  • for advanced users only, most users won't need to use the helper functions
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
imageCompression.copyExifWithoutOrientation(copyExifFromFile: File, copyExifToFile: File): Promise<File> // based on

Browsers support

IE / Edge
IE / Edge
iOS Safari
iOS Safari
IE10, IE11, Edge last 2 versions last 2 versions last 2 versions last 2 versions last 2 versions

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:

<script src=""></script>

Webp support

The webp compression is supported on major browsers. Please see for browser compatibility.

Remarks for compression to work in Web Worker

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 for browser compatibility of "OffscreenCanvas" API.

Typescript type definitions

Typescript definitions are included in the package & referenced in the types section of the package.json

Remarks on Content Security Policy (CSP)

If your website has CSP enabled and you want to use Web Worker (useWebWorker: true), please add the following to the response header content-security-policy: script-src 'self' blob:

  • blob: is for loading Web Worker script
  • is for importing this library from CDN inside Web Worker script. If you don't want to load this library from CDN, you can set your self hosted library URL in options.libURL.


  1. fork the repo and git clone it
  2. run npm run watch # it will watch code change in lib/ folder and generate js in dist/ folder
  3. add/update code in lib/ folder
  4. try the code by opening example/development.html which will load the js in dist/ folder
  5. add/update test in test/ folder
  6. npm run test
  7. push to your forked repo on github
  8. make a pull request to dev branch of this repo
Popular Compression Projects
Popular Image Compression Projects
Popular Software Performance Categories
Related Searches

Get A Weekly Email With Trending Projects For These Categories
No Spam. Unsubscribe easily at any time.
Image Compression