Chatra
Chatra

Reputation: 3139

Angular 7 - Display Images from byte in Database

I am having around 400 images all stored in database and getting those in C# code in byte[].

My requirement is very simple. I have Design class which contains Name, Code and byte[]. I am binding this class using ngFor

<div *ngFor="let design of designs" >
<img height="200" width="200"  src="{{design.data}}" />

<div>
  <h2>{{ design.name }}</h2>
  <h4>{{ design.code }}</h4>
</div>

I tried this link but it is not working for me. I used both directive and other method. Looks like few things got changed from 2 to 7.

The second answer in the above link without using directive gave me another error. Error is this

Finally, after spending more than a half day, I am unable to display image in UI. I am developing using Angular 7. What would be the best way to display images?

Upvotes: 0

Views: 5285

Answers (1)

Tachyon
Tachyon

Reputation: 2411

You're going to need to base64 encode the image bytes you are receiving from the database and then display the image using the base64 bytes.

So you can do something along the lines of the following:

var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(arrayBuffer)));

Where arrayBuffer is a buffer of the bytes, once you have gotten your base64 string you can set it to a public variable. Bear in mind that you need to append the header to the base64 string. So you if your public variable is called image then you will have to do the following:

this.image = 'data:image/jpeg;base64,' + base64String

Once you have done that you can display the iamge using the following tag:

<img id="image" [src]="image" >

Upvotes: 1

Related Questions