简体   繁体   English

如何在Angular中将本地图像文件转换为base64?

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

I have an image locally in a folder: assets/img/xyz.JPEG and I want to convert it to base64. 我在本地文件夹中有一个图像:assets / img / xyz.JPEG,我想将其转换为base64。 Kindly provide the code necessary to do so in Angular 8 请提供在Angular 8中执行此操作所需的代码

I tried using file reader and btoa but didn't work. 我尝试使用文件阅读器和btoa,但是没有用。

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

Not really sure what exactly are you trying to achieve here by doing this. 不太确定您到底要通过此方法实现什么目标。

But FileReader accepts blobs, as an argument to readAsDataURL . 但是FileReader接受blob作为readAsDataURL的参数。 So you'll have to read it from the URL using HttpClient 's get method specifying responseType as blob . 因此,您必须使用HttpClientget方法(将responseType指定为blob从URL中读取它。 The onload method on the reader can then be used to get the Base 64 url for the image. 然后可以使用阅读器上的onload方法获取图像的Base 64网址。

Here, give this a try: 在这里,尝试一下:

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);
        };

      });
  }
}

Here's a Working Sample StackBlitz for your ref. 这是供您参考的工作样本StackBlitz

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

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