Giter VIP home page Giter VIP logo

browser-image-compression's Introduction

Browser Image Compression

npm npm npm

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

Features

  • 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

open https://donaldcwl.github.io/browser-image-compression/example/basic.html

or check the "example" folder in this repo

Usage

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

async await syntax:

async function handleImageUpload(event) {

  const imageFile = event.target.files[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) {
    console.log(error);
  }

}

Promise.then().catch() syntax:

Click to expand
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);
    });
}

Installing

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="https://cdn.jsdelivr.net/npm/[email protected]/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 :)

Buy Me A Coffee

(powered by Stripe)

API

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: https://cdn.jsdelivr.net/npm/browser-image-compression/dist/browser-image-compression.js)
  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 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 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: https://caniuse.com/?search=AbortController

function handleImageUpload(event) {

  var imageFile = event.target.files[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 https://stackoverflow.com/a/32490603/10395024
imageCompression.copyExifWithoutOrientation(copyExifFromFile: File, copyExifToFile: File): Promise<File> // based on https://gist.github.com/tonytonyjan/ffb7cd0e82cb293b843ece7e79364233

Browsers support

IE / Edge
IE / Edge
Firefox
Firefox
Chrome
Chrome
Safari
Safari
iOS Safari
iOS Safari
Opera
Opera
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="https://cdnjs.cloudflare.com/ajax/libs/core-js/3.21.1/minified.min.js"></script>

Webp support

The webp compression is supported on major browsers. Please see https://caniuse.com/mdn-api_offscreencanvas_converttoblob_option_type_parameter_webp 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 https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas#browser_compatibility 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: https://cdn.jsdelivr.net

  • blob: is for loading Web Worker script
  • 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.

Contribution

  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

browser-image-compression's People

Contributors

a432511 avatar adityak74 avatar dependabot[bot] avatar donaldcwl avatar heinrich-fresh avatar jamiehaywood avatar pzi avatar raccoonback avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

browser-image-compression's Issues

Issue with Jest Test Cases

Getting the following issue, when i run test cases

TypeError: Cannot read property 'drawImage' of null
    at drawImageInCanvas (/node_modules/browser-image-compression/dist/browser-image-compression.js:8:4058)
    at $Try_1_Post (/node_modules/browser-image-compression/dist/browser-image-compression.js:8:4203)
    at /node_modules/browser-image-compression/dist/browser-image-compression.js:8:4391
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

Any ideas how to resolve this ?

Firefox: compression in Web Worker fails

When trying to use the lib in Firefox (67.0.1 (64-Bit) or Dev. Edition: 68.0b8 (64-Bit)) it yields: "Run compression in web worker failed: document is not defined , fall back to main thread"

imageCompression func alters options object

Hello! Thank you for this module.
There is an issue if imageCompression function is used in a "for" loop. If options object is defined before the loop then on each iteration function imageCompression changes options' properties:

async function compressFiles(uncompressedFiles) {
    const compressedFiles = [];
    const options = {
          maxSizeMB: 0.3,
          maxWidthOrHeight: 1280,
          useWebWorker: true,
    };
    for (let i = 0; i < uncompressedFiles.length; i++) {
      try {
        const compressedFile = await imageCompression(uncompressedFiles[i], options);
        compressedFiles.push(compressedFile);
      } catch (error) {
        console.log(error);
      }
    }
    return compressedFiles;
  }

For example, if I try to upload 3 photos and the first one has exifOrientation = 6 then the rest of the photos will be rotated as well, because exifOrientation will be in the options object after the first iteration.
I guess it is because of this line:
options.exifOrientation = options.exifOrientation || await getExifOrientation(file)

I think compress function should use a copy of options object.
I've opened PR for this issue: #71

Memory usage skyrockets when doing the compression

So the compression is working, but memory often goes through the roof - for example, compressing a 40MB jpg spikes my browser's memory usage up to 2GB. This causes crashes and inconsistent behaviour on mobile browsers.

After the process is finished, there is also about 400MB more memory being used by the browser, which never gets cleaned up and released.

Is there anything that I can do to manage the amount of a memory this process will use?

File not defined

While working in Nuxt, if I import imageCompression from "browser-image-compression"; into a compontent (page), a single page reload/refresh will throw File not defined error and freeze that window.
image
This is how it looks, every now and then it shows the actual error if it does not freeze by then.

How to compress images which are in portrait while preserving the resolution dimensions? 4608x2592

Great plugin. i m able to compress normal landscape images perfectly and their dimensions are correctly coming. however, when i try to compress an image of portrait with these dimensions 4608x2592 and raw size of 2.60 MB, the output compress file dimensions are 2098x3732 (which distorts the image ratio so it looks bad), and final size of 586 KB. File size is good but dimensions are getting messed up. can u fix this please?

I am using below options:

var options = {
maxSizeMB: 1,
useWebWorker: false
}

i even tried using the maxWidthOrHeight: 1920, but then it doesnt work for images with dimensions of 4608x2592
.. can u tell me what would be the best maxWidthOrHeight value which will be able to compress and scale most images on the web while preserving the dimensions?

Feature Request: Progress Update

It would be great if there was a prop or method to update the progress of compression.

In my app, I uploaded a 10 mb file and compressed it down to 2.5 mb. It took about 2 seconds. I had no way to show progress. What I ended up doing is showing an animated progress bar that is 100%. But it would be nice to show the compression progress as an increasing progress bar.

NPM error on running npm run test

When running "npm run test" in my project, browser-image-compression gives the following error:

(node:5212) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'createElement' of undefined
at new file (\node_modules\jsdom\lib\jsdom\browser\Window.js:374:34)
at file (\node_modules\browser-image-compression\lib\utils.js:66:5)
at new Promise ()
at img (\node_modules\browser-image-compression\lib\utils.js:66:5)
at \node_modules\browser-image-compression\lib\utils.js:124:11
(node:5212) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag
--unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:5212) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
events.js:288
throw er; // Unhandled 'error' event
^

Error: EPERM: operation not permitted, lstat '\node_modules\browser-image-compression\dist\browser-image-compression.d.ts'
Emitted 'error' event on NodeWatcher instance at:
e_watcher.js:306:14)
at callback (\node_modules\graceful-fs\polyfills.js:295:20)
at FSReqCallback.oncomplete (fs.js:166:21) {

WebpackError: ReferenceError: File is not defined

I am using browser image compression for my website using gatsby. I just import this,
import imageCompression from 'browser-image-compression';

when I start to gatsby develop everything is normal, but when I tried to gatsby build, i just got error this.

Screen Shot 2020-01-29 at 14 37 43

Larger file size after compression.

I'm seeing the file size of a jpeg increase from 1234610 bytes to 2346328 bytes - I've left the 'quality' config option as default.

Could you explain why I am seeing such a large increase in size after compression?

Thanks

Multiple compatibility issues with cordova-plugin-file

First, thank you for the plugin. It's been working great so far until we added cordova-plugin-file to our solution.

It appears that the new types for File and FileReader don't work with this plugin.

I am working on fixes that will be backwards compatible with non-cordova implementations and will submit a PR when I have it working.

Cheers!

Exif orientation support broken with iOS 13.4.1 and Safari 13.1 Desktop

In iOS 13.4.1 (released a few days ago) as well as Safari 13.1 desktop, the EXIF orientation value is no longer being handled properly, and the compressed image that is output will not have the correct orientation.

The easiest way to reproduce this is to go to the demo site https://donaldcwl.github.io/browser-image-compression/example/basic.html using a Safari or Chrome browser on a device running iOS 13.4.1 and attempt to upload the attached image. This image has orientation EXIF value of 3 (rotated 180 degrees).

The demo page will return the image rendered upside down. However, the same image on a device not running iOS 13.4.1 will return the image rendered with the proper orientation.

IMG_2119

ios 13 3

ios 13 4 1

onProgress error from 1.0.7 onwards

Very useful lib! But since upgrading from version 1.0.6 to 1.0.7 I have been receiving the following error:

index.js:70 Uncaught TypeError: n.onProgress is not a function
at Worker.handler

I could track the issue down to the new onProgress option. It seems that the default value is not working as expected when custom options are provided without an onProgress handler, e.g.:

options={{
   maxSizeMB: 600 / 1024,
   maxWidthOrHeight: 600,
   useWebWorker: true,
   maxIteration: 10,
   fileType: 'image/jpeg',
}}

My current workaround is to add

onProgress: () => null

to the options object.

Image not captured correctly

Hi

When I upload a photo the compression works fine, if I try again with same photo the image get a background black.

Import the package in Angular

Thanks for the contribution.
A quick question. After I installed this package using npm install, how do I import in Angular.

I tried import imageCompression from 'browser-image-compression'; but imageCompression doesn't exist in browser-image-compression.

Any thoughts?

Unknown error

When I try to use imageCompression, I get a very strange error.

Thrown error

My code is the easiest I can write:

imageCompression(file, {
	maxSizeMB: 10,
}).then((compressedFile) => {
	console.log("ok");
}).catch((error) => {
	console.log(error);
});

EDIT: Looks like it happens only on a specific image file... I think that it's corrupted which is very strange because all other softwares can open it.

`maxSizeMB` is violated.

When i provide following configuration

const options = { 
  maxSizeMB: 0.029,          // 29Kb
  maxWidthOrHeight: 1080 //
};

Entering this image (9.7Mb) causes the output file size to be 0.04 (40KB).

I also checked the same configuration Demo. Its also happening in Demo too.

Expected result.

Maintain a image size within given maxSizeMB even of the maxWidthOrHeight needed to be decreased more and more proportionally.

Include default quality level on options

The default quality level is hard-coded to value 1 but if it could be surfaced to the options, it would allow to use a lower value for cases where it could be reduced.

On a specific case I have, from a 5MB file, the default compression (quality = 1) would set the file size to 872KB, as if quality=0.9 (perfectly fine for my case) it would be 234KB, almost 4 times smaller file size.

Is there any reason why this was never considered?

Wrong proportions at the output

Hi, great job! But i have a some issue with proportions. I take a portrait orientation and get the output image, which is rotated and squeezed

Missig file extension "mjs".

Import package in react but i got this linting error Missing file extension "mjs" for "browser-image-compression".

getFileFromDataUrl and getDataUrlFromFile not found

version 1.0.9 installed through yarn in an angular 6 project with typescript 2.7.2
using the following

import imageCompression from "browser-image-compression";

getting in webstorm code editor

TS1192: Module '"(hidden for confidentiality.)../node_modules/browser-image-compression/dist/browser-image-compression"' has no default export.

and when compiling application getting the two following errors

error TS2339: Property 'getFileFromDataUrl' does not exist on type '(image: Blob | File, options: Options) => Promise<Blob | File>'.
error TS2339: Property 'getDataUrlFromFile' does not exist on type '(image: Blob | File, options: Options) => Promise<Blob | File>'.

i tried two implementation of in a ngrx-effect

return of ( imageCompression.getFileFromDataUrl( action.payload.data.content )
          .then( ( file: File ) => {
            const options = {
              maxSizeMB: 0.25,       
              maxWidthOrHeight: 1240,  
              useWebWorker: false
            }
            imageCompression( file, options )
              .then( (compressedFile: File ) => {
                action.payload.data.size = compressedFile.size;
                action.payload.data.type = compressedFile.type;
                imageCompression.getDataUrlFromFile( compressedFile)
                  .then( (dataUri: string ) => {
                    action.payload.data.content = dataUri;
                    return action  ;
                  })
              } )
          } )
          .catch( err => { throw err })
        )

or

private async  compress ( action ) {
    try {
      const file = await imageCompression.getFileFromDataUrl( action.payload.data.content );
      const options = {
        maxSizeMB: 0.25,          // (default: Number.POSITIVE_INFINITY)
        maxWidthOrHeight: 1240,   // compressedFile will scale down by ratio to a point that width or height is smaller than maxWidthOrHeight (default: undefined)
        useWebWorker: false
      }
      const compressedFile = await imageCompression( file, options );
      const dataUri = await imageCompression.getDataUrlFromFile( compressedFile );
      action.payload.data.content = dataUri;
      action.payload.data.size = compressedFile.size;
      action.payload.data.type = compressedFile.type;
      return action;
  } catch ( err ) {
    throw err;
  }

none of the advanced functions seems available

what is wrong ?

thanks for your help

Image rotation issue in some cases

When taking a photo on my iPhone X and running it through the imageCompression(file) method it results in a photo that is turned incorrectly. I did not specify the exifOrientation option myself as I see your code accounts for it already (THANK YOU!).

Ex:
A portrait taken photo is rotated 90 degrees counter-clockwise (notch at top) or 90 degrees clockwise (notch at bottom).
A landscape taken photo will either be correct (power button up) or upside down (power button down).

React: importing imageCompression... WEBPACK_IMPORTED_MODULE_11___default(...) is not a function

Installing the latest version of browser-image-compression and importing it in a react project leads to an error no matter what I do.

Note that it works in the example React app in this repo but I cannot use it in any projects. I have tried creating a module out of the component class and putting that in my project. I have also tried matching every dependency in the React app in mine to no avail.

The exact error is:

"Unhandled Rejection (TypeError): browser_image_compression__WEBPACK_IMPORTED_MODULE_11___default(...) is not a function"

and it occurs at the line where the imageCompression function is called.

Image larger than MaxSizeMB

Not sure if this is an bug or a limitation of PNG files, but with MaxSizeMB set to 2, my 8MB PNG file is output at 5MB.
leaf

Async/await not working as expected

Hi there. I'm trying to use browser-image-compression with async/await, not being able to do it.
I wrapped the call to have it resolve by its own and having a cleaner code as below (showing relevant parts).

const myImageCompressor = async (val, maxSizeMB, maxWidthOrHeight) => {
  const result = await imageCompressor(val, maxSizeMB, maxWidthOrHeight);
  return result;
};

Then I'm using it as:

for (let item of Object.entries(payload)) {
  let [key, val] = item;
  ...
  const maxMB = 1,      // max MBs
  maxSize = 1200; // max Size rescale
  val = myImageCompressor(val, maxMB, maxSize);
  ...
}

Problem is that val doesn't have a File but a still unsolved Promise. Is this a bug or there's anything wrong in the code above?

drawImageInCanvas method throws error in iPhone X because OffscreenCanvas is incompatible

Hi, great jobs.

// browser-image-compression.mjs
function drawImageInCanvas(e) {
  let n;
  const canvas =
    typeof OffscreenCanvas === 'function' ? new OffscreenCanvas(e.width, e.height) : document.createElement('canvas');
  const context = canvas.getContext('2d');
  console.log('>>>>>> drawImageInCanvas', canvas);
  console.log('>>>>>> drawImageInCanvas', context);
  return (
    (n =
      typeof OffscreenCanvas === 'function' ? new OffscreenCanvas(e.width, e.height) : document.createElement('canvas'))
      .getContext('2d')
      .drawImage(e, 0, 0, n.width, n.height),
    n
  );
}

new OffscreenCanvas(e.width, e.height).getContext('2d') get null when runs in iPhone X(iOS 12.1).
Maybe u should check the return value of getContext method.

Poor English, feel free to correct.

Web Worker Failing on Chrome

Chrome 75.0.3770.100 Win 10 64-bit

I do the following:

var compressionOptions = {
          maxSizeMB: 0.8,
          maxWidthOrHeight: 1920,
          useWebWorker: true,
          exifOrientation: true
        };
const imageFile = await imageCompression(
          file,
          compressionOptions
        );

and get the following in browser console:

browser-image-compression.mjs:430 Run compression in web worker failed: x is not defined , fall back to main thread

Any ideas what could be wrong? The image is correctly compressed, but without a web worker.

Not working in React

I got

TypeError: browser_image_compression__WEBPACK_IMPORTED_MODULE_15___default(...) is not a function

web worker failing on chrome with adblock turned ON , even after webworker is set to false.

Refused to create a worker from 'blob:https://site.com/3e9ce499-7750-4d8c-896b-7db16d4677c6' because it violates the following Content Security Policy directive: "script-src 'self' * 'unsafe-inline'". Note that 'worker-src' was not explicitly set, so 'script-src' is used as a fallback.

(anonymous) @ browser.img.compress.js:1
(anonymous) @ browser.img.compress.js:1
(anonymous) @ browser.img.compress.js:1
(anonymous) @ browser.img.compress.js:1
browser.img.compress.js:1 Uncaught DOMException: Failed to construct 'Worker': Access to the script at 'blob:https://site.com/3e9ce499-7750-4d8c-896b-7db16d4677c6' is denied by the document's Content Security Policy.
at https://site.com/js/browser.img.compress.js:1:7705
at https://site.com/js/browser.img.compress.js:1:7770
at https://site.com/js/browser.img.compress.js:1:165
at https://site.com/js/browser.img.compress.js:1:169

Any way to fix this, i have even turned off use web worker option by false.

Unable to use the package in react when installing using npm

Hi,
I tried installing the package in my react project using npm.
I used ES6 import. When I tried to console the imageCompression object, the output is displayed as a function.

Code is
"import imageCompression from 'browser-image-compression';
console.log(imageCompression)"

output is
"/static/media/browser-image-compression.9d2e921a.mjs"

the error I am getting is
"TypeError: __WEBPACK_IMPORTED_MODULE_1_browser_image_compression___default(...) is not a function"

Circular dependency

When you run the npm run build process, there's a warning:

(!) Circular dependency: lib/index.js -> lib/web-worker.js -> lib/index.js

There's already the import compress from './image-compression' that seems to do most of the heavy lifting and it's not like the web-worker is ever going to call another web-workers, which is possible in the current configuration. Perhaps extract the core of the runner and have index.js and web-worker.js both use that new core?

This doesn't seem to break things BTW, it's just a warning.

Image resolution

Hi,

I used this code :
imageCompression(inputFile, {maxSizeMB: 1, maxWidthOrHeight: 720, useWebWorker: true})

But the resulted dimension of the picture is 3400x2267 (the original dimension being 5184x3456)

The size is what's expected.

I have tried to remove maxSizeMB and using maxWithOrHeight only but the final image keep the original dimension AND the final file weight is much bigger than the original. The size of the original image is 4mo the final image 11mo.

Thank you.

It is failing in SSR with NextJS

Thank you for making this awesome lib that I just found.
I see that the intention is to support SSR but as of now it is throwing an Error when used in a nextjs application.

As a workaround, I have used the next/dynamic import to load my Component which uses this lib in non-ssr mode only. But it would be awesome if the lib could support SSR by default.

cheers

SecurityError on load in IE10

When attempting to use the library even just to run without web workers enabled in IE10, I am getting a SecurityError, with the following pointer on page load:
browser-image-compression.min.js, line 12 character 5652

This appears to point to: return new Worker(URL.createObjectURL(new Blob(["(

Due to this error, imageCompression is undefined later when I attempt to invoke it and the call obviously fails.

no typescript definitions

npm install @types/browser-image-compression doesn't install any types because there aren't any. I had to add an empty definitions file just to use it. Please add some types

Cannot find module 'browser-image-compression'.

I was trying to use this, but after installing I can't seem to import the module? I don't really understand how to even do what people are saying because they just say thing's like create a d.ts file and declare it there. What does that even mean?

I've had to import it like this
import imageCompression from "../../../../node_modules/browser-image-compression/dist/browser-image-compression";

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.