Prerequisites
I am trying to load and show on the page the png-image stored in Postgres as bytea (byte array).
The image in database looks like this (actually I'm not sure whether it's the best way to store small images in Postgres or not):
I'll skip my NodeJS part - nothing unusual there - just performing SQL for getting the user with his avatar image.
My solution
I looked into some similar issues as How to display Base64 images in HTML and Converting an image to base64 in angular 2 and some others as well. So I applied something similar in my Angular component:
private readonly imageFile: Observable<File|undefined> = this.currentUser.pipe(
switchMap(user => this.userService.getUserById(user?.id!)),
map(user => user.avatar),
filter(avatar => !!avatar),
);
constructor(private readonly userService: UserService) {
this.imageFile.subscribe((imageFile: File|undefined) => {
const blob = new Blob([imageFile!], {type: 'image/png'});
var reader = new FileReader();
reader.readAsDataURL(blob); // #1
// reader.readAsBinaryString(blob); // #2
reader.onload = () => {
const image = document.getElementById('loadedImage') as HTMLImageElement;
image.src = 'data:image/png;base64,' + btoa('' + reader.result); // #3
// image.src = '' + reader.result; // #4
};
});
}
In my template I have:
<img id="loadedImage" src="">
Result
The problem is that resulting image doesn't appear as loaded:
The resulting image tag is
- with code lines
#1and#3:
<img id="loadedImage" src="data:image/png;base64,ZGF0YTppbWFnZS9wbmc7YmFzZTY0LFcyOWlhbVZqZENCUFltcGxZM1Jk">
- with code lines
#1and#4:
<img id="loadedImage" src="data:image/png;base64,W29iamVjdCBPYmplY3Rd">
Possible alternatives
I also tried to replace
readAsDataURL()withreadAsBinaryString()(line#2)'data:image/png;base64,' + btoa('' + reader.result)with justreader result(line#4)
No luck in both cases.
Question
What should I change in my solution to be able to depict the loaded image?
Note: I'm using rxjs and NodeJS but I didn't include them into tags, since the problem is not related to them.