【问题标题】:How do I display a base64 image in Angular 7?如何在 Angular 7 中显示 base64 图像?
【发布时间】:2019-07-27 17:35:07
【问题描述】:

我想获取 base64 字符串并用它来显示图像。
下面是 HTML 文件。我想使用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>

我从 .ts 文件中获取 imageFileBinary。
下面是 .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?

【问题讨论】:

  • 试试这样的:&lt;img src="data:image/JPEG;base64,{{imageFileBinary}}"/&gt;
  • 如果在下载之前不知道图像类型,这可能不起作用。 (因为它总是假设数据是“JPEG”)。您应该考虑使用同时保留数据类型的 DataUrl 字符串。 (见下面我的回答)

标签: angular base64 angular7


【解决方案1】:

试试这个..

使用 javascript btoa 函数将您的图像二进制数据转换为 base64 并附加 data 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;

最后设置成角度数据绑定

<img src={{imageUrl}} />

【讨论】:

    【解决方案2】:

    您需要将已下载的数据转换为 DataUrl 才能将其用作图像源。

    这是一个完整的解决方案,它将图像下载为 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
    }
    

    here 是一个演示,以备不时之需。

    【讨论】:

      猜你喜欢
      • 2021-12-20
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2019-11-08
      • 2019-06-27
      • 1970-01-01
      相关资源
      最近更新 更多