J86
J86

Reputation: 15237

Convert Byte Array to image and display in Razor View

I am using EF 4.1 Code First and for the sake of simplicity, let's say I have the following Entity class:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Byte[] Image { get; set; }
}

I have managed to create a working Create View that allows the Addition of a Person object into the Database.

But when I come to display the details for a Person, I get stuck on displaying the image. After doing some research, I have the following:

// To convert the Byte Array to the author Image
public FileContentResult getImg(int id)
{
    byte[] byteArray = DbContext.Persons.Find(id).Image;
    return byteArray != null 
        ? new FileContentResult(byteArray, "image/jpeg") 
        : null;
}

And in the View where I am attempting to list the Person details, I have the following to get the Image to display:

<img src="@Html.Action("getImg", "Person", new { id = item.Id })" alt="Person Image" />

However the above is not working, my image source [src] attribute returns empty.

Upvotes: 43

Views: 52012

Answers (3)

sondlerd
sondlerd

Reputation: 1025

I found that the best way to display a dynamically loaded SVG image from a Model property in a Razor MVC page is to use Html.DisplayFor(..) in combination with .ToHTMLString(). For my case, have a base 64 SVG Image+XML data string stored in the model property named Image. Here is my code:

<img src='@Html.DisplayFor(model => model.Image).ToHtmlString()' />

This seemed be the only way I was able to get the SVG image to display properly in Chrome, FireFox and IE.

Cheers

Upvotes: 0

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102408

There's an even easier way of doing this if you already happen to have the image loaded in your model:

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

Doing this way you do not need to go to the server again just to fetch the image byte[] from the database as you're doing.

Upvotes: 70

Darin Dimitrov
Darin Dimitrov

Reputation: 1038850

Like this:

<img src="@Url.Action("getImg", "Person", new { id = item.Id })" alt="Person Image" />

You need Url.Action and not Html.Action because you just want to generate an url to the GetImg action. Html.Action does something entirely different.

Upvotes: 38

Related Questions