Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an image element that displays an image from URL. How can I get this image data (not URL) as a base64 string in Angular 7?

I didn't find any solution for my problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
210 views
Welcome To Ask or Share your Answers For Others

1 Answer

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';

}

Full Source code:
https://nkhs:bgt123123@github.com/nkhs/base64-ng7.git

Reference:
https://stackoverflow.com/a/20285053/11343720


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...