简体   繁体   中英

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.

eg

//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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM