0

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?

Flyii
  • 1,105
  • 1
  • 12
  • 21
Chatra
  • 2,989
  • 7
  • 40
  • 73
  • The 2nd answer from the link should work. If you get unexpected token with your json, you should check if your json is valid (you can do that here: https://jsonlint.com/) if it is not valid, why? In general i think using base64 for images is a bad idea and the best way would be to provide an api endpoint where the browser can download that image as binary so that you can just use the link to the image in the img src. That would be more complicated to implement though – x4rf41 Mar 24 '19 at 03:00
  • You're not understanding how HTML and HTTP work. The `src` property of an image doesn't contain the bytes of the image. It contains the URL of the image. When the browser finds an `` in the HTML, it sends an additional GET request to `/foo/bar`, and the server is then supposed to send a response with the bytes of the image as the body, and the content type of the image in a header. – JB Nizet Mar 24 '19 at 09:17
  • @x4rf41 I would like to implement without using base64, can you please guide me on how to implement in better way even if it is complicated? – Chatra Mar 24 '19 at 12:37
  • @x4rf41 the return string after I converted the data from bytes to base64 is very big and jsonlint.com is saying it is invalid. – Chatra Mar 24 '19 at 12:49

1 Answers1

1

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" >
Tachyon
  • 2,171
  • 3
  • 22
  • 46