Display an image contained in a byte[] with ASP.Net MVC3

26,434

Solution 1

You can create a controller action method that returns an image as a FileContentResult:

public FileContentResult Display(string id) {
   byte[] byteArray = GetImageFromDB(id);
   return new FileContentResult(byteArray, "image/jpeg");
}

Then you can create an ActionLink to the action method in the view using the image id from the model.

Solution 2

It depends on how big the image is. If it is small, you could write something to base-64 encode it and embed it in the html, like any of these.

For a concrete example from here:

<img src="data:image/gif;base64,R0lGODlhUAAPAKIAAAsLav///88PD9WqsYmApmZmZtZfYmdakyH5BAQUAP8ALAAAAABQAA8AAAPbWLrc/jDKSVe4OOvNu/9gqARDSRBHegyGMahqO4R0bQcjIQ8E4BMCQc930JluyGRmdAAcdiigMLVrApTYWy5FKM1IQe+Mp+L4rphz+qIOBAUYeCY4p2tGrJZeH9y79mZsawFoaIRxF3JyiYxuHiMGb5KTkpFvZj4ZbYeCiXaOiKBwnxh4fnt9e3ktgZyHhrChinONs3cFAShFF2JhvCZlG5uchYNun5eedRxMAF15XEFRXgZWWdciuM8GCmdSQ84lLQfY5R14wDB5Lyon4ubwS7jx9NcV9/j5+g4JADs=" alt="British Blog Directory" width="80" height="15">

If the image is of any appreciable size, you may want instead to write a route that allows lookup via some key to the image, i.e. a route like /images/{id} - in that route you fetch the image binary and use return File(bytes, contentType), additionally setting caching headers (and remember to re-check any necessary security). In your html you would just have an

<img src="/images/@imageId" ... />

(using razor syntax, but similar for aspx).

The separate route approach requires an additional hop to the server, but allows caching at the client (the inline base-64 approach puts the data on every request).

Solution 3

If you already happen to have the image loaded in your model as a byte[] array you can do this as @Marc Gravell mentions in his answer:

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

This greatly simplifies the whole process and you won't need to have a specific FileContentResult action method and hit the database again (see @Dmitry S's answer) just to fetch that byte[] array with your image/photo since you already have it loaded in your model.

Solution 4

Sounds like you'd need a new action that gets the byte array (from a database?) and returns the image via the File method....

Then generate an anchor that points to that action, that way the image can be loaded while the page is loading, speeding up the display.

Solution 5

Look at WebImage class.

http://msdn.microsoft.com/en-us/library/system.web.helpers.webimage(v=vs.99).aspx

Share:
26,434
J4N
Author by

J4N

Updated on July 09, 2022

Comments

  • J4N
    J4N almost 2 years

    I've a view with a strong type. This strong type has a field consisting of a byte[], this array contains a picture.

    Is it possible to display this image with something like @Html.Image(Model.myImage) ?

    Thank you very much