[英]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
的參數。 因此,您必須使用HttpClient
的get
方法(將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.