Manohar A
Manohar A

Reputation: 71

How do I display a base64 image in Angular 7?

I want to take the base64 string and use it to display the image.
Below is the HTML file. I want to use the base64 string and use it in the img tag:

<ion-content>
  <ion-card>
      <img src={{imageFileBinary}} />
        <ion-card-header>
            <form>
                <ion-input id="myform" type="file" name="file" (change)="postMethod($event.target.files)"></ion-input>
            </form>
        <ion-card-title>Nick</ion-card-title>
    </ion-card>
</ion-content>

I get imageFileBinary from the .ts file.
Below is the .ts file:

export class MyprofilePage implements OnInit {


  imageFileBinary;

  userDetails: UserDetails;
  constructor(private profileDetailService: ProfileDetailsService, private httpClient: HttpClient) {}

  fileToUpload;

  getProfileDetails() {
    this.profileDetailService.getUserDetails('email').subscribe((userDetails: UserDetails) => {
      this.imageFileBinary = userDetails.imageFileBinary
    });
  }
  postMethod(files: FileList) {
    this.fileToUpload = files.item(0);
    let formData = new FormData();
    formData.append('file', this.fileToUpload, this.fileToUpload.name);

    this.httpClient.post("http://localhost:8080/uploadFile", formData).subscribe((val)=> {
      console.log(val);
    });
    return false;
  }
  ngOnInit() {
    this.getProfileDetails();

  }

}


How can I use the base64 String in the img tag?

Upvotes: 5

Views: 25446

Answers (3)

hossein vatankhah
hossein vatankhah

Reputation: 214

import DomSanitizer, SafeResourceUrl like this:

import {DomSanitizer, SafeResourceUrl} from '@angular/platform-browser';

define parameter and constructor:

picture: SafeResourceUrl;
constructor(private sanitizer: DomSanitizer) {}

sanitizer the base64:

this.picture = this.sanitizer.bypassSecurityTrustResourceUrl(
  'data:image/jpg;base64,' + this.imageFileBinary);
});

show in html:

<img src={{picture}} />

Upvotes: 0

Just Shadow
Just Shadow

Reputation: 11871

You need to convert the data you've downloaded to DataUrl to be able to use it as image source.

Here is a complete solution which downloads an image as base64 data url and shows to user:

import { Component, Input, OnInit } from '@angular/core';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { map, flatMap } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  template: `
  <div>
    <img [src]="quokkaData" />
    <img [src]="quokkaAsyncData | async" /> 
  </div>`,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  public quokkaAsyncData: Observable<string>;
  public quokkaData: string;

  constructor(private httpSvc: HttpClient) { }

  ngOnInit() {
    // Method 1: Pass observer directly to template where "| async" is used.
    this.quokkaAsyncData = this.downloadDataAsBase64('https://pbs.twimg.com/media/DR15b9eWAAEn7eo.jpg');

    // Method 2: Get data from subscriber and pass to image src
    this.downloadDataAsBase64('https://pbs.twimg.com/media/DR15b9eWAAEn7eo.jpg')
      .subscribe((base64Data: string) => {
        this.quokkaData = base64Data;
      });
  }

  //#region Util methods

  private downloadDataAsBase64(url: string): Observable<string> {
    return this.httpSvc.get(url, { responseType: 'blob' }).pipe(
      flatMap(blob => {
        return this.blobToBase64(blob);
      })
    );
  }

  private blobToBase64(blob: Blob): Observable<any> {
    const fileReader = new FileReader();
    const observable = new Observable(observer => {
      fileReader.onloadend = () => {
        observer.next(fileReader.result);
        observer.complete();
      };
    });
    fileReader.readAsDataURL(blob);
    return observable;
  }

  //#region Util methods
}

And here is a demo just in case it's needed.

Upvotes: 2

Alwin Jose
Alwin Jose

Reputation: 773

try this..

Convert your image binary data to base64 using javascript btoa function and append it with data uri property.

imageUrl; //rename imageFileBinary to imageUrl

let imageBinary = userDetails.imageFileBinary; //image binary data response from api
let imageBase64String= btoa(imageBinary);
this.imageUrl = 'data:image/jpeg;base64,' + imageBase64String;

Finally set it with angular data binding

<img src={{imageUrl}} />

Upvotes: 6

Related Questions