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)?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With