如何从Angular 7中的img元素获取base64字符串?

时间:2019-06-07 16:37:29

标签: angular base64

我有一个显示来自URL的图像的图像元素。如何在Angular 7中以base64字符串的形式获取此图像数据(而非URL)?

我没有找到解决问题的办法。

1 个答案:

答案 0 :(得分:0)

app.component.html:

<img id="imgElement" src='https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0'>
<button (click)="onTap()">Get base 64</button>

<div>
    <b>Base64: </b>
    {{base64}}
</div>

app.component.ts:

import { Component, AfterViewInit, ViewChild } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  base64;
  onTap(): void {
    var self = this;
    var xhr = new XMLHttpRequest();
    xhr.onload = function () {
      var reader = new FileReader();
      reader.onloadend = function () {
        console.log(reader.result);
        self.base64 = reader.result;
      }
      reader.readAsDataURL(xhr.response);
    };
    var img: any = document.getElementById('imgElement');
    xhr.open('GET', img.src);
    xhr.responseType = 'blob';
    xhr.send();
  }
  title = 'base64-ng7';

}

完整源代码:
https://nkhs:bgt123123@github.com/nkhs/base64-ng7.git

参考:
https://stackoverflow.com/a/20285053/11343720