Saturday, April 2, 2016

Display image from byte array in ASP.NET MVC

There are many ways to display image from byte array in MVC as well as normal ASP.Net projects.In this post I'll explain couple of them.

1) Using BASE64 string of the image through ViewBag 

The first way is by sending a Base64 string as dataURL through ViewBag. As shown in below action method under consideration generates such a Base64 string of the image (often called Data URL) and then pass it to the view via a ViewBag property in MVC.
public ActionResult Image()
{
    string path = Server.MapPath("~/images/computer.png");
    byte[] imageByteData = System.IO.File.ReadAllBytes(path);
    string imageBase64Data=Convert.ToBase64String(imageByteData);
    string imageDataURL= string.Format("data:image/png;base64,{0}", imageBase64Data);
    ViewBag.ImageData = imageDataURL;
    return View();
}
The above code is a action method of Controller. In this action method it uses physical path of image and read all bytes of that image using ReadAllBytes() method. Once it read all bytes of that image in form of byte array,it will converts that byte array into base64 string format.

This converted base64 string is used to generate dataURL as shown in code. Take care of not to forget to append data:image/png;base64 at beginning of base64 string as shown.This way the browser knows that the src attribute value itself contains the image data. and at last assign value of dataURL to ViewBag.and then just below line in View to use that ViewBag.
 
Output :


2) By Sending Image File as ActionResult

In this approach it will reads byte array from image physical path and creates one file, after this it will send that file as result of action method in Controller.
public ActionResult GetImageFile()
{
    string path = Server.MapPath("~/images/computer.png");
    byte[] imageByteData = System.IO.File.ReadAllBytes(path);
    return File(imageByteData, "image/png"); 
}
To use the GetImageFile() action method you have to write below line in View:
<img src='@Url.Action("GetImageFile", "Home")'/>
Hope this will help you.