Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting image from assets and converting it to base64

Tags:

angular

I am trying to make a pdf that contains an image, but I encountered a difficulty in actually getting the image inside the code. In my project assets folder there is a list of images (svg and png), that I want to take and to convert to base64 so I can use them for my pdf.

The problem is that I couldn't find a way to actually load an image that I know it exists in that assets folder, with an absolute path (/assets/images/{imagename}.png) for example, and to load it inside the code

Here is the code I have for converting to base64:

convertImageToBase64(file: File) {
  const reader: FileReader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = (): string => {
    const base64String: string = (reader.result as string).match(/.+;base64,(.+)/)[1];
    return base64String;
  };
}

Is there a way to take the image from that path, make it somehow a File, and then convert it? Or I should use another way/Object format to do this (instead of File)?

like image 834
Artyomska Avatar asked Jan 01 '23 21:01

Artyomska


1 Answers

Just call the HttpClient's get method with { responseType: 'blob' }. This will result in the response being read as a blob Object.

You can then use FileReader to read it and convert it in base64.

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('/assets/image.jpg', { responseType: 'blob' })
      .subscribe(res => {
        const reader = new FileReader();
        reader.onloadend = () => {
          var base64data = reader.result;                
              console.log(base64data);
        }

        reader.readAsDataURL(res); 
        console.log(res);
      });
  }
}

Here's a Working Sample StackBlitz for your ref.

like image 62
SiddAjmera Avatar answered Jan 09 '23 16:01

SiddAjmera