MVC display an image that is stored as a byte array

 

So the scenario is; how do we retrieve images that are stored in a database as a byte array and display them on a page utilizing Asp.net MVC.  The major hurtle that needs to be overcome is that a HTML image tag will not accept a source if it does not have the appropriate mime-type of image.

 

To meet that requirement in the controller add a new method that returns a type of FileContentResult.  Below is an example:

public FileContentResult GetSponsorImg(int id)
{
    var image = this.BaseContext.SponsorInfoes.Find(id).SponsorLogo;
    return image != null ? new FileContentResult(image, "image/png") : null;
}

What this method accomplishes is when the id of the image is passed in we can utilize Entity Frameworks find option and search the context to see if the image exist.  In this example we are searching for a sponsors logo image.

If the image is found we create a new FileContentResult and tag it as an image/png.  If the image is not found we simple return null.

In the MVC page add an image tag that looks similar to this:

<img src="@Url.Action("GetSponsorImg", "Home", new { id = item.Id })" alt="@item.Name" title="@item.Name" />

So what this code does, it tells the image source to call the method in the controller to get the image.  As stated above the controller gets the image from the database, flags it as an image and returns it.

Advertisements
This entry was posted in Entity Framework, MVC and tagged , , . Bookmark the permalink.

5 Responses to MVC display an image that is stored as a byte array

  1. NoName says:

    You’re checking for null but what if your query returns null on the line
    var image = this.BaseContext.SponsorInfoes.Find(id).SponsorLogo;
    then you’ll get an exception trying to get SponsorLogo of an null object.

  2. nt says:

    Just a learner wanting to say thanks!

  3. mandlaanil says:

    Can you give me perform all curd operations using mvc,
    I want to insert images also using database,
    please give me complete example for this.
    I am new to MVC

  4. Bone Appe says:

    Thank you, I tried with many different code and this work for me.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s