Friday, January 15, 2016

Display images in ASP.NET MVC using custom HtmlHelper

Here's a simple Image Helper for showing known image types. I've tested this for old format such as bitmaps and images with OLE headers.
This helper sets the image width and height with fixed values. You may change it dynamically or update this helper to accept parameters for width and height.
C# Code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
/// <summary>
/// Helper for showing images
/// </summary>
public static MvcHtmlString ImageLink(this HtmlHelper htmlHelper, byte[] photo, string id) {
 string imageSrc = null;
 if (photo != null) {
  using(MemoryStream ms = new MemoryStream()) {
   string imageBase64 = string.Empty;
   Image xImage = (Bitmap)((new ImageConverter()).ConvertFrom(photo));
   if (ImageFormat.Bmp.Equals(xImage.RawFormat)) {
    // strip out 78 byte OLE header (don't need to do this for normal images)
    ms.Write(photo, 78, photo.Length - 78);
   } else {
    ms.Write(photo, 0, photo.Length);
   }
   imageBase64 = Convert.ToBase64String(ms.ToArray());
   imageSrc = string.Format("data:image/jpeg;base64,{0}", imageBase64);
  }
 }

 return new MvcHtmlString("<img id='" + id + "' src='" + imageSrc + "' alt=\"Image\" style=\"height:150px;width:150px;\" />");
}
If your HtmlExtension class is inside a folder in your project such as Helpers, make sure to add them in web.config inside the Views folder to make it accessible for the views. (EmployeeProfile is the namespace of the project and HtmlHelpers is the folder name)
<namespaces>
 <add namespace="System.Web.Mvc" />
 <add namespace="System.Web.Mvc.Ajax" />
 <add namespace="System.Web.Mvc.Html" />
 <add namespace="System.Web.Optimization"/>
 <add namespace="System.Web.Routing" />
 <add namespace="EmployeeProfile" />
 <add namespace="EmployeeProfile.Helpers" />
</namespaces>
Call the helper inside the view:
@Html.ImageLink(item.Photo, "mainPhoto")
Sample Screenshot:

Cheers! :-)

0 comments:

Post a Comment