How do I display a base64 image in Angular 7?

我是研究僧i 提交于 2020-06-29 06:10:35

问题


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?

回答1:


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}} />



回答2:


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.



来源:https://stackoverflow.com/questions/57226912/how-do-i-display-a-base64-image-in-angular-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!