本文介绍了如何在Angular 7中显示base64图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用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? 

解决方案

您需要将已下载的数据转换为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
}

此处是一个演示,以防万一.

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?

解决方案

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.

这篇关于如何在Angular 7中显示base64图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 08:40