10

I'm using blazor webassembly and I need to display an image that stored as byte array in the client side.

I tried

in C#:

imagesrc= Convert.ToBase64String(imageBytes);
imageDataURL = string.Format("data:image/jpeg;base64,{0}", imagesrc);

in markup:

<img src="@imageDataURL" />

but no image displayed just icon that no image.

is there any other way?

5
  • It should have kind-of worked. Any errors in the F12 console? Commented Sep 5, 2021 at 12:30
  • @HenkHolterman no, no errors in console Commented Sep 5, 2021 at 12:35
  • And when you use Inspect (F12, Elements), how does the <img> look? Commented Sep 5, 2021 at 12:36
  • @HenkHolterman is it matter if I'm displaying the image in the client side? the image stored as bytes no paths Commented Sep 5, 2021 at 12:37
  • @HenkHolterman when inspect it it looks like this <img src="data:image/jpeg;base64,PHN2Z............(the bytes as base64)"/> Commented Sep 5, 2021 at 12:39

3 Answers 3

9

I was curious which image format you specified instead of jpeg and like you said under @Henk answer it is svg as it starts with PHN2Z...

That doesn't mean you have to use some svg to jpeg converter, just adjust data uri type appropriately:

imageDataURL = string.Format("data:image/svg+xml;base64,{0}", imagesrc);

Heres quick blazor playground which displays data uri for various image files

Sign up to request clarification or add additional context in comments.

1 Comment

svg would be a lot smaller and faster than jpg.
5

A jpg file has a standard header. So even with different images I would expect the first few characters of the base64 to be the same.

When I convert a jpg to base64 it starts with "/9j/4AAQ"

So I think your data is not a (valid/complete) jpg file.

2 Comments

the image was svg before got its bytes and I used svg instead of jpg but still the same thing.
Thanks a lot I tried to get a jpeg image bytes now and displayed.
5

Try this in your code:

<img src="data:image;base64, @System.Convert.ToBase64String(imageBytes) />

Where "imageBytes" is your byte[] image.

1 Comment

Pretty good solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.