2

I have an image locally in a folder: assets/img/xyz.JPEG and I want to convert it to base64. Kindly provide the code necessary to do so in Angular 8

I tried using file reader and btoa but didn't work.

var reader = new FileReader();
var binaryString = reader.readAsDataURL('assets/img/xyz.JPEG');
var image = btoa(binaryString);
Monsters
  • 63
  • 2
  • 7
  • @HereticMonkey, that actually gets the image from `` Here OP is asking for reading it from a URL. – SiddAjmera Jul 21 '19 at 13:49
  • 1
    Fair enough... there are enough duplicates to go around... [How to convert image into base64 string using javascript](https://stackoverflow.com/q/6150289/215552), [CONVERT Image url to Base64](https://stackoverflow.com/q/22172604/215552) – Heretic Monkey Jul 21 '19 at 13:55
  • @HereticMonkey, the solutions to [CONVERT Image url to Base64](https://stackoverflow.com/questions/22172604/convert-image-url-to-base64) provide a non-angular way of doing things though. Mostly by creating a canvas using `document.createElement`. Which isn't really recommended. Still, links are helpful. :) – SiddAjmera Jul 21 '19 at 14:09
  • @SiddAjmera Non-Angular? It's JavaScript... And there are several answers on both questions that do not use canvas. – Heretic Monkey Jul 21 '19 at 14:57
  • Sure there are. I just though to let the OP get just one answer so that they don't have to wander from one thread to another in order to achieve what they're trying to. – SiddAjmera Jul 21 '19 at 23:08

1 Answers1

4

Not really sure what exactly are you trying to achieve here by doing this.

But FileReader accepts blobs, as an argument to readAsDataURL. So you'll have to read it from the URL using HttpClient's get method specifying responseType as blob. The onload method on the reader can then be used to get the Base 64 url for the image.

Here, give this a try:

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

      });
  }
}

Here's a Working Sample StackBlitz for your ref.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110