Welcome folks today in this blog post we will be using the ngx-photo-editor
library to build image editor
with live preview to crop,scale
and rotate
images using typescript in browser. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new angular
project using the below command as shown below
ng new sampleproject
cd sampleproject
And after that you need to install the below libraries
using the below command as shown below
npm i ngx-photo-editor
And after that you will see the below directory
structure of the angular app as shown below
And now you need to go to angular.json
file of your angular project and copy paste this below css
line of the library inside the styles
section as shown below
angular.json
1 2 3 4 |
"styles": [ "src/styles.css", "node_modules/ngx-photo-editor/photo-editor.css" ], |
And now we need to go to app.component.html
file and copy paste the following code
app.component.html
1 2 |
<input type="file" (change)="fileChangeHandler($event)"> <img [src]="output?.base64" alt=""> |
As you can see in the above html
code we have the input field
element where we allow the user to select the image
file and then we have the image
displayed with live preview
using the base64 code of the image.
And now we need to go to app.component.ts
file and copy paste the below code
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import { Component } from '@angular/core'; import { NgxCroppedEvent,NgxPhotoEditorService } from 'ngx-photo-editor'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { title = 'angular image editor'; output?: NgxCroppedEvent; constructor(private service: NgxPhotoEditorService) {} fileChangeHandler($event: any) { this.service.open($event, { aspectRatio: 4 / 3, autoCropArea: 1 }).subscribe(data => { this.output = data; }); } } |
As you can see in the above typescript
code we are importing the ngx-photo-editor
module at the very top and then we are passing the ngxPhotoEditor Service
inside the constructor. And then we are defining the method that we have binded on the input
field inside it we are using the open()
method of the image editor to show the image inside the modal editor
to perform the operations such as crop,scale and rotate as shown below.