Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

How to get base64 string from img element in Angular 7?

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

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

1 Reply

0 votes
by (71.8m points)

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:[email protected]/nkhs/base64-ng7.git

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...