Generate Base64 String And Display Image In Angular 12

In this article, we will learn how to create a Base64 string in Angular 12.

What is Base64?

  • Base64 is mainly used when there is a need to encode data that needs to be stored and transferred over media that are designed to deal with ASCII (American Standard Code For Information Interchange).
  • This can be used to ensure that the data remain intact without modification during transport.


  • Removes separate HTTP(Hypertext Transfer Protocol) Requests for image loading by wrapping encoded image code inside CSS or HTML.
  • Image encoded data can be saved inside the database and can generate image files. Just in case we lost the image file copy.


  • Though Base64 increases performance is careful. Doing so will increase the image size by approximately 20-25%. then what it is actually in its binary form.
  • Even if we apply to gzip compression, doing so will only decrease CSS file size to around 10-12%.
    IE6 & IE7 do not support Data URI which means Base64 images will not be loaded in ie6 & ie7 browsers.


  • Basic knowledge of Angular.
  • Code editor likes VS Code.

Create a new project using this command.

ng new Base64Angular

Open the app.component.ts file and add the following code.

import { Component } from '@angular/core';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  isImageSaved: boolean = false;
  cardImageBase64: string = '';

  constructor() {

  CreateBase64String(fileInput: any) {
    if ( &&[0]) {
      const reader = new FileReader();
      reader.onload = (e: any) => {
        const image = new Image();
        image.src =;
        image.onload = rs => {
          const imgBase64Path =;
          this.cardImageBase64 = imgBase64Path;         
          this.isImageSaved = true;

Now open app.component.html and add the following code.

  <div class="form-group">
    <fieldset class="form-group">
      <label>Upload Image</label>
      <div class="custom-file fileInputProfileWrap">
        <div class="row col-md-12">
          <input type="file" (change)="CreateBase64String($event)" class="fileInputProfile form-control">
        <div class="img-space">
          <ng-container *ngIf="isImageSaved;">
            <img [src]="cardImageBase64" style="width: 100px;height:100px;" />

Now run the project using this command.

ng serve


If you have any queries from this article then tell me in a comment.

Thank you.

Also, check 


  1. Swapnil Dasharath Kadu

    Great Tutorial

    1. Thank you


Submit a Comment

Your email address will not be published.


Select Categories