Welcome folks today in this blog post we will be using the ngx-image-drawing
library to draw on images
using colors and download it inside the browser 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-image-drawing
npm i file-saver
And after that you will see the below directory
structure of the angular app as shown below
Now you need to go to app.module.ts
file and include the imageDrawingModule
inside the imports array as shown below
app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { ImageDrawingModule } from 'ngx-image-drawing'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, ImageDrawingModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule{} |
And now we need to go to app.component.html
file and copy paste the following code
app.component.html
1 2 3 4 5 6 |
<image-drawing [src]="imageUrl" [outputMimeType]="'image/jpeg'" [outputQuality]="0.8" (save)="save($event)"> </image-drawing> |
As you can see in the above html
code we have the image-drawing
directive and inside it we are passing some config options such as the image url
variable and then we are passing the mimetype or extension of the output image and then the quality
of the output image. And lastly we are binding a event
function whenever we click the save button this function will execute to download the image
after you made the modifications.
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 |
import { Component } from '@angular/core'; import * as FileSaver from 'file-saver' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { title = 'angular image editor'; imageUrl = "https://cdn.pixabay.com/photo/2023/01/22/14/10/dinner-7736494_640.jpg" save(img: any){ console.log(img) FileSaver.saveAs(img, 'result.jpg'); } } |
As you can see in the above typescript
code we are importing the image from the pixabay
website using the url. And then we have written the method of saving
the image inside the browser using the filesaver
module for that we are getting the blob
data and using the saveAs()
method to download the image as an attachment as shown below.