4

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?

0

2 Answers 2

8

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.

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

1 Comment

This also works without the png image type. <img src="data:image;base64,@System.Convert.ToBase64String(Model.Image)" alt=""/>
2

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

Comments

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.