{"id":13456261,"url":"https://github.com/Donaldcwl/browser-image-compression","last_synced_at":"2025-03-24T09:31:54.637Z","repository":{"id":38291526,"uuid":"98123131","full_name":"Donaldcwl/browser-image-compression","owner":"Donaldcwl","description":"Image compression in web browser","archived":false,"fork":false,"pushed_at":"2024-03-08T18:16:16.000Z","size":15152,"stargazers_count":1396,"open_issues_count":54,"forks_count":167,"subscribers_count":8,"default_branch":"master","last_synced_at":"2025-03-20T19:09:55.347Z","etag":null,"topics":["compress-image","image-compression","image-compressor","image-upload","jpg-compression","png-compression","webp-compression"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Donaldcwl.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-07-23T20:20:51.000Z","updated_at":"2025-03-20T03:07:19.000Z","dependencies_parsed_at":"2024-06-18T12:27:43.809Z","dependency_job_id":null,"html_url":"https://github.com/Donaldcwl/browser-image-compression","commit_stats":{"total_commits":251,"total_committers":13,"mean_commits":"19.307692307692307","dds":"0.10756972111553786","last_synced_commit":"d933bc8e483a9853ed2b57338e035e8c45e40dc7"},"previous_names":[],"tags_count":21,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Donaldcwl%2Fbrowser-image-compression","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Donaldcwl%2Fbrowser-image-compression/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Donaldcwl%2Fbrowser-image-compression/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Donaldcwl%2Fbrowser-image-compression/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Donaldcwl","download_url":"https://codeload.github.com/Donaldcwl/browser-image-compression/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245243372,"owners_count":20583614,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["compress-image","image-compression","image-compressor","image-upload","jpg-compression","png-compression","webp-compression"],"created_at":"2024-07-31T08:01:18.825Z","updated_at":"2025-03-24T09:31:54.625Z","avatar_url":"https://github.com/Donaldcwl.png","language":"JavaScript","funding_links":[],"categories":["JavaScript","HTML"],"sub_categories":[],"readme":"# Browser Image Compression\n[![npm](https://img.shields.io/npm/v/browser-image-compression.svg)](https://www.npmjs.com/package/browser-image-compression)\n[![npm](./coverage/badge.svg)](https://github.com/Donaldcwl/browser-image-compression)\n[![npm](https://img.shields.io/npm/l/browser-image-compression.svg)](https://github.com/Donaldcwl/browser-image-compression)\n\nJavascript module to be run in the web browser for image compression.\n\n## Features\n- 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.\n- **Multi-thread** (web worker) non-blocking compression is supported through options.\n\n\n## Demo / Example\nopen https://donaldcwl.github.io/browser-image-compression/example/basic.html\n\nor check the \"[example]\" folder in this repo\n\n\n## Usage\n```html\n\u003cinput type=\"file\" accept=\"image/*\" onchange=\"handleImageUpload(event);\"\u003e\n```\n### async await syntax:\n```javascript\nasync function handleImageUpload(event) {\n\n  const imageFile = event.target.files[0];\n  console.log('originalFile instanceof Blob', imageFile instanceof Blob); // true\n  console.log(`originalFile size ${imageFile.size / 1024 / 1024} MB`);\n\n  const options = {\n    maxSizeMB: 1,\n    maxWidthOrHeight: 1920,\n    useWebWorker: true,\n  }\n  try {\n    const compressedFile = await imageCompression(imageFile, options);\n    console.log('compressedFile instanceof Blob', compressedFile instanceof Blob); // true\n    console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeMB\n\n    await uploadToServer(compressedFile); // write your own logic\n  } catch (error) {\n    console.log(error);\n  }\n\n}\n```\n### Promise.then().catch() syntax:\n\u003cdetails\u003e\n  \u003csummary\u003eClick to expand\u003c/summary\u003e\n  \n  ```javascript\n  function handleImageUpload(event) {\n\n    var imageFile = event.target.files[0];\n    console.log('originalFile instanceof Blob', imageFile instanceof Blob); // true\n    console.log(`originalFile size ${imageFile.size / 1024 / 1024} MB`);\n\n    var options = {\n      maxSizeMB: 1,\n      maxWidthOrHeight: 1920,\n      useWebWorker: true\n    }\n    imageCompression(imageFile, options)\n      .then(function (compressedFile) {\n        console.log('compressedFile instanceof Blob', compressedFile instanceof Blob); // true\n        console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeMB\n\n        return uploadToServer(compressedFile); // write your own logic\n      })\n      .catch(function (error) {\n        console.log(error.message);\n      });\n  }\n  ```\n\u003c/details\u003e\n\n## Installing\n### Use as ES module:\nYou can install it via npm or yarn\n```bash\nnpm install browser-image-compression --save\n# or\nyarn add browser-image-compression\n```\n```javascript\nimport imageCompression from 'browser-image-compression';\n```\n(can be used in frameworks like React, Angular, Vue etc)\n\n(work with bundlers like webpack and rollup)\n\n### (or) Load UMD js file:\nYou can download imageCompression from the [dist folder][dist].\n\nAlternatively, you can use a CDN like [delivrjs]:\n```html\n\u003cscript type=\"text/javascript\" src=\"https://cdn.jsdelivr.net/npm/browser-image-compression@2.0.2/dist/browser-image-compression.js\"\u003e\u003c/script\u003e\n```\n\n\n## Support\nIf this project helps you reduce the time to develop, you can buy me a cup of coffee :)\n\n\u003ca href=\"https://donaldcwl.github.io/donation/\" target=\"_blank\"\u003e\u003cimg src=\"https://cdn.buymeacoffee.com/buttons/v2/default-red.png\" alt=\"Buy Me A Coffee\" height=60 width=217 \u003e\u003c/a\u003e\n\n(powered by Stripe)\n\n## API\n### Main function\n```javascript\n// you should provide one of maxSizeMB, maxWidthOrHeight in the options\nconst options: Options = { \n  maxSizeMB: number,            // (default: Number.POSITIVE_INFINITY)\n  maxWidthOrHeight: number,     // compressedFile will scale down by ratio to a point that width or height is smaller than maxWidthOrHeight (default: undefined)\n                                // but, automatically reduce the size to smaller than the maximum Canvas size supported by each browser.\n                                // Please check the Caveat part for details.\n  onProgress: Function,         // optional, a function takes one progress argument (percentage from 0 to 100) \n  useWebWorker: boolean,        // optional, use multi-thread web worker, fallback to run in main-thread (default: true)\n  libURL: string,               // optional, the libURL of this library for importing script in Web Worker (default: https://cdn.jsdelivr.net/npm/browser-image-compression/dist/browser-image-compression.js)\n  preserveExif: boolean,        // optional, use preserve Exif metadata for JPEG image e.g., Camera model, Focal length, etc (default: false)\n\n  signal: AbortSignal,          // optional, to abort / cancel the compression\n\n  // following options are for advanced users\n  maxIteration: number,         // optional, max number of iteration to compress the image (default: 10)\n  exifOrientation: number,      // optional, see https://stackoverflow.com/a/32490603/10395024\n  fileType: string,             // optional, fileType override e.g., 'image/jpeg', 'image/png' (default: file.type)\n  initialQuality: number,       // optional, initial quality value between 0 and 1 (default: 1)\n  alwaysKeepResolution: boolean // optional, only reduce quality, always keep width and height (default: false)\n}\n\nimageCompression(file: File, options: Options): Promise\u003cFile\u003e\n```\n\n#### Caveat\nEach browser limits [the maximum size](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas#maximum_canvas_size) of a browser Canvas object. \u003cbr/\u003e\nSo, we resize the image to less than the maximum size that each browser restricts. \u003cbr/\u003e\n(However, the `proportion/ratio` of the image remains.)\n\n#### Abort / Cancel Compression\nTo use this feature, please check the browser compatibility: https://caniuse.com/?search=AbortController\n```javascript\nfunction handleImageUpload(event) {\n\n  var imageFile = event.target.files[0];\n\n  var controller = new AbortController();\n\n  var options = {\n    // other options here\n    signal: controller.signal,\n  }\n  imageCompression(imageFile, options)\n    .then(function (compressedFile) {\n      return uploadToServer(compressedFile); // write your own logic\n    })\n    .catch(function (error) {\n      console.log(error.message); // output: I just want to stop\n    });\n  \n  // simulate abort the compression after 1.5 seconds\n  setTimeout(function () {\n    controller.abort(new Error('I just want to stop'));\n  }, 1500);\n}\n```\n\n### Helper function\n- for advanced users only, most users won't need to use the helper functions\n```javascript\nimageCompression.getDataUrlFromFile(file: File): Promise\u003cbase64 encoded string\u003e\nimageCompression.getFilefromDataUrl(dataUrl: string, filename: string, lastModified?: number): Promise\u003cFile\u003e\nimageCompression.loadImage(url: string): Promise\u003cHTMLImageElement\u003e\nimageCompression.drawImageInCanvas(img: HTMLImageElement, fileType?: string): HTMLCanvasElement | OffscreenCanvas\nimageCompression.drawFileInCanvas(file: File, options?: Options): Promise\u003c[ImageBitmap | HTMLImageElement, HTMLCanvasElement | OffscreenCanvas]\u003e\nimageCompression.canvasToFile(canvas: HTMLCanvasElement | OffscreenCanvas, fileType: string, fileName: string, fileLastModified: number, quality?: number): Promise\u003cFile\u003e\nimageCompression.getExifOrientation(file: File): Promise\u003cnumber\u003e // based on https://stackoverflow.com/a/32490603/10395024\nimageCompression.copyExifWithoutOrientation(copyExifFromFile: File, copyExifToFile: File): Promise\u003cFile\u003e // based on https://gist.github.com/tonytonyjan/ffb7cd0e82cb293b843ece7e79364233\n```\n\n\n## Browsers support\n\n| [\u003cimg src=\"https://raw.githubusercontent.com/alrra/browser-logos/master/src/edge/edge_48x48.png\" alt=\"IE / Edge\" width=\"24px\" height=\"24px\" /\u003e](http://godban.github.io/browsers-support-badges/)\u003cbr/\u003eIE / Edge | [\u003cimg src=\"https://raw.githubusercontent.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png\" alt=\"Firefox\" width=\"24px\" height=\"24px\" /\u003e](http://godban.github.io/browsers-support-badges/)\u003cbr/\u003eFirefox | [\u003cimg src=\"https://raw.githubusercontent.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png\" alt=\"Chrome\" width=\"24px\" height=\"24px\" /\u003e](http://godban.github.io/browsers-support-badges/)\u003cbr/\u003eChrome | [\u003cimg src=\"https://raw.githubusercontent.com/alrra/browser-logos/master/src/safari/safari_48x48.png\" alt=\"Safari\" width=\"24px\" height=\"24px\" /\u003e](http://godban.github.io/browsers-support-badges/)\u003cbr/\u003eSafari | [\u003cimg src=\"https://raw.githubusercontent.com/alrra/browser-logos/master/src/safari-ios/safari-ios_48x48.png\" alt=\"iOS Safari\" width=\"24px\" height=\"24px\" /\u003e](http://godban.github.io/browsers-support-badges/)\u003cbr/\u003eiOS Safari | [\u003cimg src=\"https://raw.githubusercontent.com/alrra/browser-logos/master/src/opera/opera_48x48.png\" alt=\"Opera\" width=\"24px\" height=\"24px\" /\u003e](http://godban.github.io/browsers-support-badges/)\u003cbr/\u003eOpera |\n| --------- | --------- | --------- | --------- | --------- | --------- |\n| IE10, IE11, Edge| last 2 versions| last 2 versions| last 2 versions| last 2 versions| last 2 versions\n\n### IE support\nThis 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.\n\nYou can include the following script to load the core-js polyfill:\n```html\n\u003cscript src=\"https://cdnjs.cloudflare.com/ajax/libs/core-js/3.21.1/minified.min.js\"\u003e\u003c/script\u003e\n```\n\n### Webp support\nThe webp compression is supported on major browsers. Please see https://caniuse.com/mdn-api_offscreencanvas_converttoblob_option_type_parameter_webp for browser compatibility.\n\n\n## Remarks for compression to work in Web Worker\nThe 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.\n\n\n## Typescript type definitions\nTypescript definitions are included in the package \u0026 referenced in the `types` section of the `package.json`\n\n\n## Remarks on Content Security Policy (CSP)\nIf your website has CSP enabled and you want to use Web Worker (useWebWorker: true), please add the following to the response header\n`content-security-policy: script-src 'self' blob: https://cdn.jsdelivr.net`\n\n- `blob:` is for loading Web Worker script\n- `https://cdn.jsdelivr.net` 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`.\n\n\n## Contribution\n1. fork the repo and git clone it\n2. run `npm run watch` # it will watch code change in lib/ folder and generate js in dist/ folder\n3. add/update code in lib/ folder\n4. try the code by opening example/development.html which will load the js in dist/ folder\n5. add/update test in test/ folder\n6. `npm run test`\n7. push to your forked repo on github\n8. make a pull request to dev branch of this repo\n\n[dist]: https://github.com/Donaldcwl/browser-image-compression/tree/master/dist\n[example]: https://github.com/Donaldcwl/browser-image-compression/tree/master/example\n[delivrjs]: https://cdn.jsdelivr.net/\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FDonaldcwl%2Fbrowser-image-compression","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FDonaldcwl%2Fbrowser-image-compression","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FDonaldcwl%2Fbrowser-image-compression/lists"}