简体   繁体   中英

How to convert local image file to base64 in Angular?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM