In this post we will learn to fetch image from a database. I have taken Northwind database as an example. Employee table of the Notrhwind database stores a Photo using the Image type. We will fetch data from the Photo column (type: Image) in the MVC application.

image

Let us start with the Controller. In the Index action all the Employees are fetched using the EmployeeRepository.


public ActionResult Index()
        {
            return View(_employeeRepository.List);
        }

Note: I am using repository pattern and the Entity framework. However you can fetch data directly using the Entity framework without the repository pattern.

In the View, you should convert fetched photo in a byte array as shown below. For normal photo you don’t need to subtract 78 from the length. However OLE photos it is required.


<td>
            @{ byte[] photo = item.Photo;
             string imageSrc = null;
             if (photo != null)
             {
                 MemoryStream ms = new MemoryStream();
                 ms.Write(photo, 78, photo.Length - 78);
                 string imageBase64 = Convert.ToBase64String(ms.ToArray());
                 imageSrc = string.Format("data:image/jpeg;base64,{0}", imageBase64);
             }
            }           

            <img src="@imageSrc" alt="Image" />
        </td>

In above code snippet manually we are creating Memory Stream and then converting that to byte array. However in MVC library is available to do this task for you.

image

You can use Convert.ToBase64String() method to convert the fetched image into an encode string. This function is overloaded with four different set of parameters. I am passing byte array, offset value, length and format option to create the encoded string from the image byte array. So this approach can be replaced as follows:


  <td>

            <img src="data:image/png;base64,@Convert.ToBase64String(item.Photo,78,item.Photo.Length-78 ,
            Base64FormattingOptions.None)"
                 alt="Image" /> 

        </td>

You should able to view fetched images in the application. Happy coding.

Advertisements

5 thoughts on “Fetching Image from database in ASP.NET MVC 5 application

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