GithubHelp home page GithubHelp logo

dfa1234 / ngx-image-compress Goto Github PK

View Code? Open in Web Editor NEW
83.0 3.0 36.0 9.3 MB

Angular library for uploading and compressing images

Home Page: https://image-library.app

License: MIT License

TypeScript 85.74% JavaScript 1.35% HTML 12.03% SCSS 0.88%
angular image-processing compression canvas upload-images

ngx-image-compress's People

Contributors

byronigoe avatar davi01100100 avatar dependabot[bot] avatar detobel36 avatar dfa1234 avatar modestinoandre avatar neerajkumar161 avatar rafraph avatar snyk-bot avatar turyunus 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

Watchers

 avatar  avatar  avatar

ngx-image-compress's Issues

filter gif images

If I load a gif it is converted into a static image. Is there a way to exclude gif images from the compress process?

Please add an MIT licence

I would like to consider using this on a project but I am only allowed to use items that have a licence. Would you be willing to add an MIT licence to the project?

Expose getOrientation api publically

I use compress method directly and don't use your upload method. If you can make your getOrientation method available in the api it will be great.

just compress and resize if width bigger than a given value

I'm trying to achieve to just compress and resize if width bigger than a given value

something like:

const compressed = await this.imageResizerService.compressFile(
        blobInfo.blobUri(), DOC_ORIENTATION.Default,100, 80,this.config.maxWidth);

the compressed file is always bigger (filesize) than original file, is it normal?

Invalid image - onerror event not handled, promise never rejected

Hi,
thanks for this awesome lib. I have a problem though. When I try to compress a corrupted / invalid file, I never get any resolve or reject from compressFile's promise. I've looked though your code and the problem seems to be that you handle the onload event (image-compress.ts:118) on the Image object you use for the compression, but you don't handle onerror to reject the promise in case of invalid images.

Please add the .onerror callback containing a reject(error), so the app doesn't loop forever.

Thanks!

vector style PNG compressed to bigger size

Most vector style PNG result in bigger size after compressed.

example files below compressed with
imageCompress.compressFile(res.image, res.orientation, 40, 100):
download
Before compress: 4922 byte
After compress: 7118 byte

download
Before compress: 9342 byte
After compress: 12330 byte
compressed

Multiple Image compress

How can I pass array of images blob to uploadfile function ? Could someone please provide me an idea/example to compress multiple file using ngx-image-compress?

not work in safari on iphone x

Hello, there is a problem with the safari browser, if you try to run an example on an iPhone, then there is no reaction.

Promise does not resolve on abortion

Hey i don't know if this is a real problem, but i wondered why the promise of .uploadFile() does not resolve or reject, when the user decides to abort the file selection instead of choosing a file.

I would have expected the promise to be rejected in that case.

I am using it like this:

async memberFunction(): Promise<void> {
  const compressionInput = await this.customService.uploadImage();
  // code here never gets executed on abortion of the file selection
  ...
}

Where the customService just wraps the uploadFile function of the NgxImageCompressService like so:

uploadFile(): Promise<CompressionInput> {
  return this.imageCompress.uploadFile();
}

Doesn't this mean, that an async thread or something gets stuck waiting for the promise to resolve or be rejected?

Greetings

upload only image format

while uploading it is taking all format in popup window , i want to show only image format like jpeg, png like formats can you help me in this

File not uploading from android device

Hi

I am currently working on a project in Angular 12. I used the function uploadAndGetImageWithMaxSize().
It works fine in the windows enviornment, the image gets uploaded and resized, but when I run it on an android device the upload dialog opens and select the image and press done, nothing happens. I'm not even getting any error codes or anything.

Is there a known issue for android devices?

EXIF Orientation may already be applied by the canvas

CanvasRenderingContext2D.drawImage() automatically rotates the JPEG image based on the EXIF Orientation flag. Therefore applying the detected orientation a second time will rotate the image too much.

Perhaps it did not used to be the case, and perhaps it is not the case in some browsers, but at least it is in Chrome 95.0.4638.69

Here is an image I made for testing. The arrow points to the left in the raw data, but the EXIF Orientation value of 6 causes it to point up.
up_exif

Building a library alongside with Ivy and non-Ivy transpilation for retrocompatibility

@davi01100100 @gethinoakes @dfa1234 @byronigoe @davi01100100 I am using ngx-image-compress-legacy plugin for my angular project(Angular verision 8) . Plugin works in local host when ng serve. but it throws error when trying to take production build(ng build --prod).
ERROR in ./src/app/admin/transactions/edit-transaction-modal.component.ngfactory.js Module not found: Error: Can't resolve 'ngx-image-compress' in 'C:\angular\src\app\admin\transactions'

I import 'NgxImageCompressService' in my component.ts and module file like following.
in component file

import { NgxImageCompressService } from ngx-image-compress-legacy;
constructor(){private imageCompress: NgxImageCompressService}

in module file

import {NgxImageCompressService} from "ngx-image-compress-legacy";
providers: [NgxImageCompressService]

Its Works in local(ng serve) but throw error in build(ng build --prod).

Image compression fails on Firefox Android

I'm running into an issue with Firefox on Android (Related #38 ). Apparently, larger files 3-4MB's will cause the app to remain in a 'stuck' state because the compression somehow doesn't work (it doesn't resolve or reject the promise).

In the case below, both console.logs will not get outputted because the promise doesn't resolve or reject:

async compressImage(file: string, fileSource: File): Promise<void | File> {
    const orientation = await this.imgCompress.getOrientation(fileSource);
    return this.imgCompress
		.compressFile(file, orientation, 50, 50)
		.then((image) => {
                         console.log('image', image);
			const imageBlob = this.dataURItoBlob(image.split(',')[1]);
			const imageFile = new File([imageBlob], fileSource.name, {
				type: 'image/jpeg',
			});
			return imageFile;
		 })
                 .catch((err: any) => {
                     console.log('err compress', err);
                  })
	}

Looking in the source code I noticed that in the compress() function the onload event won't fire when larger images are passed to the compressFile() function. Smaller images somehow work and the onload event is fired. I'm not sure why this is the case in firefox considering it works how it's suppose to work in Chrome (also with larger images).

Sometime uploadFile().then() function does not fire

Hello,
i have an angular 8 app with this simple button (as written in your example) :

<button class="ng2-file-input-drop-container" (click)="selectedImage()">{{browseText}}</button>
and the method:

`public selectedImage() {

 this.imageCompress.uploadFile()
 .then(
   ({image, orientation}) => {...})`

There are some cases where the promise then function is not called.
It is not clear when it happens, because it seems a random issue.

Maybe it could be related to the Promise resolve.

The problem happens both in Chrome and Firefox, latest versions.

In same places i read something about zone.js and FileReader().onload event that doesn't work properly. Maybe can be usefull.

Best regards
Antonio.

Listen to change event in iOS

We ran into an issue where it is not working in iOS. We built an angular PWA and Safari has some issues by listening to the change event. There were no problems in Chrome or Firefox.
We found this related issue (https://stackoverflow.com/questions/47664777/javascript-file-input-onchange-not-working-ios-safari-only) and fixed the corresponding file "ngx-image-compress.js". Right before inputElement.click() in the uploadFile() method we implemented document.getElementById("mediacontainer").appendChild(inputElement);.
For iOS the file has to be actually in the DOM so we append it to an element. Perhaps even document.appendChild(inputElement); would work but we haven't tested this.

Would it be possible to add this or something like this to your existing implementation?

Thanks, Nico

Get access to the File names

Hello.

Excellent library. Is there a way to get access to the File names when using:

this.imageCompress.uploadFile()
.then((singleFile: { image: string, orientation: number }) => //...

Regards

uploadFileOrReject not rejecting on Chrome on Android

I tested out the this.imageCompress.uploadFileOrReject() on desktop, and when I dont select a file, the rejection is handled properly in catch block but when I tried the same thing in Chrome on android, the catch block is not executed at all.

error log wrong orientation value

sir,

i had an issue with your default config.
when i'm trying to use the compression function it works well.
but got an error output log 'Wrong orientation value'

what shoud i do ?

i'm using angular 5 btw, with serverside rendering configuration.

thanks before sir.

Resize the image

Hello,
(don't know if it can be an "issue")
Could you, please, think about adding a method (or compressFile method parameters) which can resize (increase/decrease pixels) the image ?

Update 1: ratio parameter isn't really convenient if I wish to resize to exactly 100px an image, for example
Thank you

Show spinner or loading circle while it compresses a slightly large file

I would like to show a spinner that indicates the file is being compressed. how would I achieve that, as putting it before the 'this.imageCompress.uploadFile()' prevents me from stopping the spinner if the user cancels the operation. And putting it inside the 'then' block kind of defeats the purpose as it takes a little while before it actually proceeds to the 'then' block. Thanks for your help.

` compressFile() {

this.isloading = true;
this.imageCompress.uploadFile().then(({image, orientation}) => {

  this.imgResultBeforeCompress = image;
  console.warn('Size in bytes was:', this.imageCompress.byteCount(image));
  
  this.imageCompress.compressFile(image, orientation, 75, 50).then(
    result => {
      this.isloading = false;
      console.log(result);
      this.imgResultAfterCompress = result;
      console.warn('Size in bytes is now:', this.imageCompress.byteCount(result));
    }
  );
  
});

}`

Doesn't work with version 12 of Angular

Hi,

I'm trying to use with version 12 of Angular, but you don't appear to have a version that's compatible?

$ node --version
v16.15.0
$ npm --version
8.10.0

npm ERR! Conflicting peer dependency: @angular/[email protected]
npm ERR! node_modules/@angular/common
npm ERR!   peer @angular/common@"^11.0.1" from [email protected]
npm ERR!   node_modules/ngx-image-compress
npm ERR!     ngx-image-compress@"^11.0.3" from the root project

Any help gratefully received.

Many thanks

Neil

I got the RangeError when I choose 0 size file

Hello,
First of all, I appreciate your implementing this.
When I choose 0 size file on a selection dialog for the image, I got the RangeError as below.
image
Do you have any idea about it?
Thank you for your answer in advance.

Issue using with Ionic: I get black images from camera and gallery

I'm using this plugin for compression in an ionic project, and whenever I upload images from the camera or gallery, I get black images. I used the ionic camera plugin for the camera and gallery. Please assist or guide me in resolving this matter as soon as possible.

Quality of Image

Is there a way to change the quality of the image dynamically.

Question for code

Hi for line 182 for ngx-image-compress.js , there is a comment "important for safari: we need to wait for onload event ". May I know what does that mean and is it related to the issue regarding the image not displaying on ios safari ?

Compress image to given size

At the description is said:
"Angular utility for compressing images to a satisfying size, that you can choose"
But you don't seem to be able to choose the target size for the image.

I can only choose the quality from 0-100 to compress and to get the size I want the only way is to try and error until it gives the size I want.

Am I missing something?
Thank you

Expose fileToDataURL Api publicaly

Hello.
I use compress method directly and don't use your upload method, instead i use classic file input and a custom drag and drop directive.
So i must convert File to DataUrl before compressing it.

If you can make your fileToDataURL method available in the api it will be great and saves me to externalize your method.

best regards

EDIT // i forgot to mention that i use the legacy build in angular 9.

Can't resolve DOC_ORIENTATION

DOC_ORIENTATION cannot be accessed because it is not exported by the library, and results in an error such as:

Module not found: Error: Can't resolve 'ngx-image-compress/lib/image-compress' in '...'

How to use it on input type file

Hello, i want to use this library to compress a image inserted by user in input type file. But i dont understand in your documentation if this library is compatibility for this situation. Thanks!

License info

On npm.org the license is set to 'none'. Can it be, or do you have plans to also update it to MIT? We would like to leverage your package, but are unable unless the package is explicitly marked MIT on the npm.org site.

Thanks in advance

insufficient RAM memory

sometimes when uploading an image it is consuming all the phone's memory and forcing to exit the app

Ivy update

Will there be an update for ivy distribution?

image

image not being shown in production mode

The library works ok in debug and also published (production mode) on my pc, but when i publish it on a production server it doesn't show the image (no console warnings on errors).

It might not be an library issue but I still have no way of tracking this.
This are the dependencies:
"@angular/animations": "^7.2.15",
"@angular/cdk": "^7.3.7",
"@angular/common": "7.2.15",
"@angular/compiler": "7.2.15",
"@angular/core": "7.2.15",
"@angular/forms": "7.2.15",
"@angular/http": "7.2.15",
"@angular/material": "^7.3.7",
"@angular/platform-browser": "7.2.15",
"@angular/platform-browser-dynamic": "7.2.15",
"@angular/platform-server": "7.2.15",
"@angular/pwa": "^0.13.9",
"@angular/router": "7.2.15",
"@angular/service-worker": "7.2.15",
"@ngrx/store": "^7.4.0",
"@nguniversal/module-map-ngfactory-loader": "6.0.0",
"@types/file-saver": "^2.0.1",
"ang-jsoneditor": "^1.7.7",
"aspnet-prerendering": "^3.0.1",
"bootstrap": "^4.3.1",
"core-js": "^2.5.4",
"file-saver": "^2.0.2",
"jquery": "^3.4.0",
"jsoneditor": "^5.33.0",
"jwt-decode": "^2.2.0",
"mat-select-filter": "^2.3.3",
"ngx-image-compress": "^7.2.4",
"ngx-spinner": "^7.1.4",
"popper.js": "^1.14.3",
"rxjs": "^6.5.1",
"zone.js": "^0.8.29"

In the markup i use a simple img
<img [src]="image" class="imagePreview">
And this is the .ts method:
compressFile() { this.image = ''; this._imageCompress.uploadFile().then(({ image, orientation }) => { let imageSize: number = this._imageCompress.byteCount(image); //IF THE UPLOADED FILE IS BIGGER THAN 10Mb WE PROMPT THE USER if (imageSize > 10000000) { this._utility.showNotification('The image is too big', 0); return; } this._imageCompress.compressFile(image, orientation, 50, 50).then( result => { this.image = result; } ); }); }

`cannot contain special characters` error in the console, sometimes happening

Hi David

When uploading file as per windows File size is 1.56 MB.

image

But on running Ngx Compress the byte count is coming at 10 MB.
In debug mode you can see the byte Count in yellow as 10.42

image

I can send you the image for testing on your email. Please let me know, I don't want to upload it on public domain.

And it is giving this error on client side, which I can't reproduce.
`cannot contain special characters in for this file itself. I don't know the reason.

Can you please guide what seems to be the issue.

The output type of compress method is always png.

Hi
I replace 173 Line:let mime = imageDataUrlSource.substr(5, imageDataUrlSource[0].length);
to
let mime = imageDataUrlSource.substr(5, imageDataUrlSource.split(';')[0].length - 5);
And the output image type will be the same with original.

How to use this library?

import {ImageCompress} from "ngx-image-compress"; // To get your image data source string (aka "data:image/jpeg:base64...") ImageCompress.uploadFile(...) // To start the compression ImageCompress.compress(...)

This is the only thing given in your doc. But I want to know how can I use this? Can you post a working example with <input type="file">

problem during migration to angular 9

Hi folks,

The ngx-image-compress library works fine with Angular 8, but I was trying to migrate our project to Angular 9 and I faced a lot of problems, I tried all the new versions of the library and the result was not as expected.
I also saw another issue similar to mine in this link Please update to support Angular 9
Could you please update to support Angular 9?

Thanks.

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.