Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load Image Src from Byte[] Asp.Net MVC 3

I have an ASP.net MVC 3 application where I want to store an image as bytes in the model and then load it from the model into the src attribute of an html image tag.

e.g.

//Property in Model
 public byte[] Image { get; set; }

But when I try this it errors:

<img src = "@Model.Image" alt=""/>

How can I load the image from bytes? I want to avoid calling the Controller again to get the image as a FileResult.

Is it possible?

like image 516
user1513030 Avatar asked Dec 27 '22 18:12

user1513030


1 Answers

The easiest way is something like this:

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

This assumes a PNG payload and is not very well supported by legacy browsers.

I would actually recommend saving it to disk and letting your web server host it up separately.

like image 142
John Gietzen Avatar answered Dec 29 '22 10:12

John Gietzen