Friday, January 15, 2016

Simple ASP.NET MVC Image Helper in C#

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;\" />");
}

Call the helper inside the view:
@Html.ImageLink(item.Photo, "mainPhoto")

Sample Screenshot:

Cheers! :-)

0 comments:

Post a Comment