Thursday, November 8, 2012

Show Bitmap Image in ASP.NET MVC View from Database with Image data type.

I encountered this weird problem rendering bitmap image from a database table that a friend of mine develops in his company. The task is to display the image on the mvc view. I thought it was a gif or jpeg or png format. But to my surprise as I rendered the binary data on webpage, the image was a bitmap type.. The code to show the bitmap image is as follows. That is to render the bitmap image into a jpeg format.
Code:
      public ActionResult ShowCategories()  
      {   
        var model = from n in oContext.ApplianceCategories  
              select n;  
        return View(model);        
      }  

      public void ShowImage(int id)  
      {  
        var image = (from m in oContext.ApplianceCategories  
               where m.CategoryID == id  
               select m.Picture).FirstOrDefault();  
        TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));  
        Bitmap bitmap1 = (Bitmap)tc.ConvertFrom(image);  
        bitmap1.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);  
      } 
I got the trick from stack overflow... Cheers!

2 comments:

  1. The task is to display the image on the mvc view. I thought it was a gif or jpeg or png format.

    ReplyDelete
  2. Showing images on MVC in jpeg or png format is pretty straightforward.
    For .bmp images is a bit tricky.

    ReplyDelete