簡體   English   中英

如何在Angular中將本地圖像文件轉換為base64?

[英]How to convert local image file to base64 in Angular?

我在本地文件夾中有一個圖像:assets / img / xyz.JPEG,我想將其轉換為base64。 請提供在Angular 8中執行此操作所需的代碼

我嘗試使用文件閱讀器和btoa,但是沒有用。

var reader = new FileReader();
var binaryString = reader.readAsDataURL('assets/img/xyz.JPEG');
var image = btoa(binaryString);

不太確定您到底要通過此方法實現什么目標。

但是FileReader接受blob作為readAsDataURL的參數。 因此,您必須使用HttpClientget方法(將responseType指定為blob從URL中讀取它。 然后可以使用閱讀器上的onload方法獲取圖像的Base 64網址。

在這里,嘗試一下:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';

  constructor(private http: HttpClient) { }

  ngOnInit() {
    this.http.get('https://avatars0.githubusercontent.com/u/5053266?s=460&v=4', { responseType: 'blob' })
      .subscribe(blob => {
        const reader = new FileReader();
        const binaryString = reader.readAsDataURL(blob);
        reader.onload = (event: any) => {
          console.log('Image in Base64: ', event.target.result);
        };

        reader.onerror = (event: any) => {
          console.log("File could not be read: " + event.target.error.code);
        };

      });
  }
}

這是供您參考的工作樣本StackBlitz

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM