user1513030
user1513030

Reputation: 67

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?

Upvotes: 4

Views: 7484

Answers (2)

RRB
RRB

Reputation: 51

You can directly embed the image as a base64 encoded string.

Example:

<img src="data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub/
/ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcpp
V0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7" 
width="16" height="14" alt="embedded folder icon">

The size of the data is limited to 32 KiB in Internet Explorer 8. Additionally base64 results in an overhead of 33%.

More information: http://en.wikipedia.org/wiki/Data_URI_scheme

Upvotes: 2

John Gietzen
John Gietzen

Reputation: 49534

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.

Upvotes: 8

Related Questions