【问题标题】:How to convert local image file to base64 in Angular?如何在Angular中将本地图像文件转换为base64?
【发布时间】:2019-07-21 21:37:28
【问题描述】:

我在本地文件夹中有一张图片:assets/img/xyz.JPEG,我想将其转换为 base64。请提供在 Angular 8 中执行此操作所需的代码

我尝试使用文件阅读器和 btoa 但没有用。

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

【问题讨论】:

  • @HereticMonkey,实际上是从 <input type="file" /> 获取图像,这里 OP 要求从 URL 读取它。
  • @HereticMonkey,CONVERT Image url to Base64 的解决方案提供了一种非角度的做事方式。主要是通过使用document.createElement 创建一个画布。这不是真的推荐。尽管如此,链接还是很有帮助的。 :)
  • @SiddAjmera 非 Angular?它是 JavaScript ......而且这两个问题都有几个不使用画布的答案。
  • 当然有。我只是想让 OP 只得到一个答案,这样他们就不必为了实现他们想要的目标而从一个线程徘徊到另一个线程。

标签: angular image base64


【解决方案1】:

不太确定您这样做究竟想达到什么目的。

但是 FileReader 接受 blob,作为 readAsDataURL 的参数。因此,您必须使用HttpClientget 方法从URL 中读取它,将responseType 指定为blob。然后可以使用阅读器上的onload 方法获取图像的 Base 64 url​​。

来,试试看:

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

      });
  }
}

这里有一个Working Sample StackBlitz 供您参考。

【讨论】:

  • 它不工作。我想要的只是从 assets/image/xyz.JPEG 读取本地图像并将其转换为 base64
  • 谢谢,它有效。由于没有注入它,我遇到了 http 错误。
  • 抱歉,这个 stackblitz 没有模板
  • @RejzozroutkoTezbir,不确定你的意思。我可以看到 StackBlitz 工作正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-26
  • 1970-01-01
  • 2014-09-14
相关资源
最近更新 更多