Select Page
This entry has been published on 2016-06-01 and may be out of date.

Last Updated on 2016-06-01.

[:en]Scenario

You have an SQL datatable which contains a BLOB column to save images direcly in your DB as binary and want to show the images on your website.

Solution

Create your EntityFramework and Controller with the common wizards and methods.

Because you cannot directly give a Byte Array to your browser, you have to edit your .cshtml file to insert the images directly into your HTML code as Base64 strings:

@foreach (var item in Model)
{
     @{
       String img64 = Convert.ToBase64String(item.image);
       String img64Url = string.Format("data:image/"+item.imagetype+";base64,{0}", img64); //imagetype can be e.g. gif, jpeg, png etc.
      }
      <img src="@img64Url"/>
}

A method which offers the images via Controller would be to add ActionResult methods (and/or parameters) for your images.

In your Controller:

public ActionResult GetImage()
{
    byte[] imageByteData = yourmodel.yourtable...yourImage;
    return File(imageByteData, "image/png"); 
}

//UPDATE 2016-06-07: 
//Some Browsers like IE do not seem to accept the ContentType parameter of File() and change it to GIF, which may result in lower image quality!
//Better use this code:
public ActionResult GetImage()
{
   System.IO.MemoryStream ms = new System.IO.MemoryStream();
   yourImage.Save(ms, resultImageType); //or use your Byte[] directly with Memorystream constructor
   ms.Position = 0;
   return new FileStreamResult(ms, "image/png");
}

Now the src attribute of the image tag should point to /Home/GetImage.

In your View:

<img src='@Url.Action("GetImage", "Home")'/>

 

Reference[:]