Installations
npm install ngx-image-compress
Developer Guide
Typescript
No
Module System
ESM
Node Version
20.15.1
NPM Version
10.7.0
Releases
Contributors
Unable to fetch Contributors
Languages
TypeScript (85.75%)
HTML (12.07%)
JavaScript (1.3%)
SCSS (0.88%)
Developer
Download Statistics
Total Downloads
3,052,658
Last Day
1,743
Last Week
10,017
Last Month
82,659
Last Year
1,014,765
GitHub Statistics
87 Stars
284 Commits
36 Forks
3 Watching
5 Branches
11 Contributors
Package Meta Information
Latest Version
18.1.5
Package Id
ngx-image-compress@18.1.5
Unpacked Size
169.16 kB
Size
41.60 kB
File Count
23
NPM Version
10.7.0
Node Version
20.15.1
Publised On
26 Jul 2024
Total Downloads
Cumulative downloads
Total Downloads
3,052,658
Last day
-25.7%
1,743
Compared to previous day
Last week
-46.2%
10,017
Compared to previous week
Last month
-10.6%
82,659
Compared to previous month
Last year
23.6%
1,014,765
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
1
Peer Dependencies
2
ngx-image-compress
Angular utility for compressing images to a satisfying size, that you can choose
Import
1npm i ngx-image-compress
- For visualizing code examples: https://stackblitz.com/edit/ngx-image-compress
- For performance tests, in particular on your mobile, please do not use stackbliz, put this production-ready application: https://image-library.app
- Compatible with any Angular version > 9
- If you use Angular version < 9, you can use
npm install ngx-image-compress@view-engine
Angular 13+ differ as there is no need to import the service in your module. You can inject the service in the constructor of your component
directly.
For any angular version before 13, you should first import the service in your module, like this:
1import {NgxImageCompressService} from 'ngx-image-compress'; 2 3@NgModule({ 4 declarations: [AppComponent], 5 imports: [BrowserModule], 6 providers: [NgxImageCompressService], 7 bootstrap: [AppComponent], 8}) 9export class AppModule {}
Usage
Here how to use the service in your component.
Using upload and compress function, independently
This option is giving control over the compression process.
compressFile() signature is detailed here
1import {Component} from '@angular/core'; 2import {NgxImageCompressService} from 'ngx-image-compress'; 3 4@Component({ 5 selector: 'app-root', 6 template: ` 7 <button (click)="compressFile()">Upload and compress Image</button> 8 <img [src]="imgResultBeforeCompression" *ngIf="imgResultBeforeCompression" /> 9 <img [src]="imgResultAfterCompression" *ngIf="imgResultAfterCompression" /> 10 `, 11}) 12export class AppComponent { 13 constructor(private imageCompress: NgxImageCompressService) {} 14 15 imgResultBeforeCompression: string = ''; 16 imgResultAfterCompression: string = ''; 17 18 compressFile() { 19 this.imageCompress.uploadFile().then(({image, orientation}) => { 20 this.imgResultBeforeCompression = image; 21 console.log('Size in bytes of the uploaded image was:', this.imageCompress.byteCount(image)); 22 23 this.imageCompress 24 .compressFile(image, orientation, 50, 50) // 50% ratio, 50% quality 25 .then(compressedImage => { 26 this.imgResultAfterCompression = compressedImage; 27 console.log('Size in bytes after compression is now:', this.imageCompress.byteCount(compressedImage)); 28 }); 29 }); 30 } 31}
Performing a single upload, and compressing automatically to a given max size
Quicker and effortless method.
Getting directly an image at a maximum of "X" MegaBytes, using a built-in algorithm:
1import {Component} from '@angular/core'; 2import {NgxImageCompressService} from 'ngx-image-compress'; 3 4@Component({ 5 selector: 'app-root', 6 template: ` 7 <button (click)="compressFile()">Upload and compress Image</button> 8 <img [src]="imgResult" *ngIf="imgResult" /> 9 `, 10}) 11export class AppComponent { 12 constructor(private imageCompress: NgxImageCompressService) {} 13 14 imgResult: string = ''; 15 16 compressFile() { 17 const MAX_MEGABYTE = 2; 18 this.imageCompress 19 .uploadAndGetImageWithMaxSize(MAX_MEGABYTE) // this function can provide debug information using (MAX_MEGABYTE,true) parameters 20 .then( 21 (result: string) => { 22 this.imgResult = result; 23 }, 24 (result: string) => { 25 console.error( 26 "The compression algorithm didn't succed! The best size we can do is", 27 this.imageCompress.byteCount(result), 28 'bytes' 29 ); 30 this.imgResult = result; 31 } 32 ); 33 } 34}
Same method but without the upload step
1this.imageCompress.getImageWithMaxSizeAndMetas({image: 'base64ValueFromYourUpload'},MAX_MEGABYTE).then
Multiple files support
For uploading multiple files, instead of using
1this.imageCompress.uploadFile() 2 .then((singleFile: { image: string, fileName:string, orientation: number }) => //...
You can use
1this.imageCompress.uploadMultipleFiles() 2 .then((arrayOfFiles: { image: string, fileName:string, orientation: number }[]) => //...
Behavior if no files have been selected
With uploadFile()
and uploadMultipleFiles()
, nothing will happen when the user is selecting nothing, close the file selection, and
cancel the upload.
If you want the upload promise to reject in such case, please use: uploadFileOrReject()
or uploadMultipleFilesOrReject()
instead.
compressFile() signature
The signature of compressFile() is:
compressFile(image, orientation, ratio, quality, maxWidth, maxHeight)
Parameter | Type | Description |
---|---|---|
image | string | DataUrl (string) representing the image |
orientation | number | EXIF Orientation value using the DOC_ORIENTATION enum value |
ratio | number | Maximum scale factor as a percentage (optional, default: 50) 1 |
quality | number | JPEG quality factor as a percentage (optional, default: 50) 2 |
maxWidth | number | Maximum width in pixels if you need to resize (optional, default: 0 - no resize) |
maxHeight | number | Maximum height in pixels if you need to resize (optional, default: 0 - no resize) |
[1] Ratio: "50" will decrease the resolution of each dimension by 2, i.e.: image of 2000 X 1500 pixels will become 1000 X 750 pixels, while the whole resolution will be reduced by 4.
[2] Quality: For more info about this parameter, read this guide
How it works under the hood?
We will use Renderer2, and transform the image using HTML canvas encrustation. In fact you can use the static version in the library and import renderer by yourself, or replace it with another DOM abstraction, using RendererFactory2.
There are mainly two advantage for using Renderer2 abstraction over direct DOM manipulation (by using ElementRef
or window.document
directly).
- Angular keeps the component and the view in sync using templates, data binding, and change detection. All of them are bypassed when we update the DOM Directly.
- DOM Manipulation works only in a browser. In the future we will not be able to use other platforms like web worker, in-server (for Server-Side Rendering), in a mobile or a desktop application, etc... where there is no browser.
- The DOM APIs do not sanitize the data. Hence, it is possible to inject a script, thereby, opening our app to XSS injection attacks.
That's being said, please note that because of some iOS limitations/bugs when using Renderer2, we still are using window.document
API, for
the upload part only (not the canvas itself).
Change log
2023/02/14
- Update transpilation builder to angular 15 (Every angular version from 9+ are still supported, for version bellow 9 please check https://www.npmjs.com/package/ngx-image-compress-legacy)
- iOS version 13+ devices are now well recognized, and the upload method using native DOM api is used in accordance to it. This should help a lot of Ionic developers.
2022/05/24
- Every angular version from 9+ are now supported.
- No need to update the library after each angular release, by using now semantic versionning.
- Every version before 9 are dropped because angular 13 only compile library ivy-compatible.
- Anyway, if you really need to use this library in you old angular app we created here a npm transpiled version in compatibily mode with View Engine: https://www.npmjs.com/package/ngx-image-compress-legacy
2022/05/10
- Adding new API to reject promise if the user close the upload windows and no files are selected (
uploadFileOrReject
anduploadMultipleFileOrReject
)
New functions avoid any breaking change in existing code, no changes are necessary, you can still useuploadFile
oruploadMultiple
. With these, the promise stays silent when the user cancel the upload selection. - Adding the file name in the upload result
2022/02/22
- Fix Exif rotation for new version of Chrome 79+
- Native upload for Safari browser
2022/01/19
- Implementing a built-in algorithm, looping several times, to reach a desired max size in Megabytes
- Readme updates and docs in method signature directly
2022/01/04
- Readme update
- CI/CD with github action
2021/12/21
- Update to Angular 13
- Upload multiple file at once
- Add support for resizing image size (compressFile() is now accepting maxWidth and maxHeight paramaters)
- Cleanup types
- Invalid image rejection
- General refactoring
2021/11/14
- Added support for max size
2020/11/18
- Update to Angular 11
- Fix upload for iOS
- Expose getOrientation api publically
2019/07/01
- Update to Angular 8 (angular 7 is enough)
- Fix DOC_ORIENTATION import (not a required import)
2019/01/09
- Since Angular 6 include its own packaging system, I no longer need my webpack config to build it.
- Everything is working in angular 7 without complaint now (test app is on github)
2018/10/04
- Adding Live example.
- Everything is now working and tested but I will make some arrangement to the code in
index.ts
before submitting it again tonpm
, in order to make it more handy.
2017/12/06
- Upload to Github
- Need some fixes and tests to be use as a static library
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
packaging workflow detected
Details
- Info: Project packages its releases by way of GitHub Actions.: .github/workflows/publish-on-npm.yml:9
Reason
dependency not pinned by hash detected -- score normalized to 4
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/on-merge.yml:14: update your workflow using https://app.stepsecurity.io/secureworkflow/dfa1234/ngx-image-compress/on-merge.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/on-merge.yml:19: update your workflow using https://app.stepsecurity.io/secureworkflow/dfa1234/ngx-image-compress/on-merge.yml/master?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/on-merge.yml:37: update your workflow using https://app.stepsecurity.io/secureworkflow/dfa1234/ngx-image-compress/on-merge.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/on-pull-request.yml:14: update your workflow using https://app.stepsecurity.io/secureworkflow/dfa1234/ngx-image-compress/on-pull-request.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/on-pull-request.yml:19: update your workflow using https://app.stepsecurity.io/secureworkflow/dfa1234/ngx-image-compress/on-pull-request.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/publish-on-npm-view-engine.yml:14: update your workflow using https://app.stepsecurity.io/secureworkflow/dfa1234/ngx-image-compress/publish-on-npm-view-engine.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/publish-on-npm-view-engine.yml:19: update your workflow using https://app.stepsecurity.io/secureworkflow/dfa1234/ngx-image-compress/publish-on-npm-view-engine.yml/master?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/publish-on-npm-view-engine.yml:25: update your workflow using https://app.stepsecurity.io/secureworkflow/dfa1234/ngx-image-compress/publish-on-npm-view-engine.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/publish-on-npm.yml:14: update your workflow using https://app.stepsecurity.io/secureworkflow/dfa1234/ngx-image-compress/publish-on-npm.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/publish-on-npm.yml:19: update your workflow using https://app.stepsecurity.io/secureworkflow/dfa1234/ngx-image-compress/publish-on-npm.yml/master?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/publish-on-npm.yml:31: update your workflow using https://app.stepsecurity.io/secureworkflow/dfa1234/ngx-image-compress/publish-on-npm.yml/master?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/publish-on-npm.yml:39: update your workflow using https://app.stepsecurity.io/secureworkflow/dfa1234/ngx-image-compress/publish-on-npm.yml/master?enable=pin
- Info: 0 out of 8 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 4 third-party GitHubAction dependencies pinned
- Info: 4 out of 4 npmCommand dependencies pinned
Reason
Found 1/22 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/on-merge.yml:1
- Warn: no topLevel permission defined: .github/workflows/on-pull-request.yml:1
- Warn: no topLevel permission defined: .github/workflows/publish-on-npm-view-engine.yml:1
- Warn: no topLevel permission defined: .github/workflows/publish-on-npm.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 10 are checked with a SAST tool
Reason
30 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92
- Warn: Project is vulnerable to: GHSA-qwcr-r2fm-qrc7
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-pxg6-pf52-xh8x
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-rv95-896h-c2vc
- Warn: Project is vulnerable to: GHSA-qw6h-vgh9-j6wx
- Warn: Project is vulnerable to: GHSA-jchw-25xp-jwwc
- Warn: Project is vulnerable to: GHSA-cxjh-pqwp-8mfp
- Warn: Project is vulnerable to: GHSA-c7qv-q95q-8v27
- Warn: Project is vulnerable to: GHSA-78xj-cgh5-2h22
- Warn: Project is vulnerable to: GHSA-2p57-rm9w-gvfp
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-mwcw-c2x4-8c55
- Warn: Project is vulnerable to: GHSA-9wv6-86v2-598j
- Warn: Project is vulnerable to: GHSA-rhx6-c78j-4q9w
- Warn: Project is vulnerable to: GHSA-7fh5-64p2-3v2j
- Warn: Project is vulnerable to: GHSA-gcx4-mw62-g8wm
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
- Warn: Project is vulnerable to: GHSA-m6fv-jmcg-4jfg
- Warn: Project is vulnerable to: GHSA-cm22-4g7w-348p
- Warn: Project is vulnerable to: GHSA-f5x3-32g6-xq36
- Warn: Project is vulnerable to: GHSA-353f-5xf4-qw67
- Warn: Project is vulnerable to: GHSA-c24v-8rfc-w8vw
- Warn: Project is vulnerable to: GHSA-8jhw-289h-jh2g
- Warn: Project is vulnerable to: GHSA-4vvj-4cpr-p986 / GHSA-64vr-g452-qvp3
- Warn: Project is vulnerable to: GHSA-9cwx-2883-4wfx
- Warn: Project is vulnerable to: GHSA-wr3j-pwj9-hqq6
- Warn: Project is vulnerable to: GHSA-3h5v-q93c-6h6q
- Warn: Project is vulnerable to: GHSA-8hc4-vh64-cxmj
Score
3.5
/10
Last Scanned on 2024-12-30
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to ngx-image-compress
fd-ngx-image-compress
Angular utility for compressing images to a satisfying size, that you can choose
@digitalascetic/ngx-pica
Angular (LTS) module to resize images files in browser
@picturelink/ngx-image-compress
Angular utility for compressing images to a satisfying size, that you can choose
ngx-alldone-image-compress
Angular utility for compressing image to a satisfying size, that you choose