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.
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.
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