简体   繁体   English

如何在Angular 7中显示base64图像?

[英]How do I display a base64 image in Angular 7?

I want to take the base64 string and use it to display the image. 我想使用base64字符串并使用它来显示图像。
Below is the HTML file. 以下是HTML文件。 I want to use the base64 string and use it in the img tag: 我想使用base64字符串并在img标签中使用它:

 <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. 我从.ts文件中获得了imageFileBinary。
Below is the .ts file: 下面是.ts文件:

 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? 

try this.. 尝试这个..

Convert your image binary data to base64 using javascript btoa function and append it with data uri property. 使用javascript btoa函数将图像二进制数据转换为base64,并附加数据uri属性。

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

You need to convert the data you've downloaded to DataUrl to be able to use it as image source. 您需要将下载的数据转换为DataUrl,才能将其用作图像源。

Here is a complete solution which downloads an image as base64 data url and shows to user: 这是一个完整的解决方案,可以下载图像作为base64数据url并显示给用户:

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. 是一个演示,以防万一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM