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.
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.
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.
Leave a Reply