Welcome folks today in this blog post we will be converting image to base64
code and display it inside the textarea using the observables
in angular 14. 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 sampleapp
cd sampleapp
Now we need to include the formsModule
inside the app.module.ts
file as shown below
app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import { BrowserModule } from "@angular/platform-browser"; import { NgModule } from "@angular/core"; import { FormsModule } from '@angular/forms'; import { AppComponent } from "./app.component"; @NgModule({ declarations: [AppComponent], imports: [BrowserModule,FormsModule], providers: [], bootstrap: [AppComponent] }) export class AppModule {} |
Now we need to go to app.component.html
file and copy paste the below html
code as shown below
app.component.html
1 2 3 4 5 6 |
<input type="file" (change)="onChange($event)" /> <div *ngIf="myimage"> <img [src]="myimage" width="200px" height="200px" alt="" /> <textarea rows="30" cols="60" [(ngModel)]="base64code"></textarea> </div> |
As you can see we have the input
field where we allow the user to upload
the image file and we have binded the (change)
event handler we are executing the onChange()
method. And then we are displaying the image using the ngIf
directive and also we have the textarea where we will be showing the base64
code of the image.
And now we need to go to app.component.ts
file and copy paste the following 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 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
import { Component } from '@angular/core'; import { Observable, Subscriber } from 'rxjs'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { title = 'imgtobase64'; myimage!: Observable<any>; base64code!: any onChange = ($event: Event) => { const target = $event.target as HTMLInputElement; const file: File = (target.files as FileList)[0]; console.log(file); this.convertToBase64(file) }; convertToBase64(file: File) { const observable = new Observable((subscriber: Subscriber<any>) => { this.readFile(file, subscriber); }); observable.subscribe((d) => { console.log(d) this.myimage = d this.base64code = d }) } readFile(file: File, subscriber: Subscriber<any>) { const filereader = new FileReader(); filereader.readAsDataURL(file); filereader.onload = () => { subscriber.next(filereader.result); subscriber.complete(); }; filereader.onerror = (error) => { subscriber.error(error); subscriber.complete(); }; } } |
As you can see we are importing the observables
and then we are using the fileReader
to read the image
which is selected by the user and then we are displaying the base64
code inside the textarea.