How to display image byte array in an img tag in ASP.NET and C#

While developing the upload image(s) feature in your application you come to a decision to take, which is shall I upload the image in a folder with naming mechanism or shall I upload the image with it’s name and save this name in the database or shall I save the image as byte array in the database. In the first 2 options you can view the image by writing it’s URL in the “src” attribute of the image tag but what if you want to make some security or coding before displaying the image and you decided to save the image in the database as byte array and then you want to display this image in the <img> tag so how can we do that ?!!

First to know how to do that we need to go deeper on how the browser react when you set the <img src=”Your Image URL.jpeg”/>. The browser detect from the src attribute that an http request to your image url must be done and wait for the response data. The browser receive the http response of the request done but what are the data available in this response that allow the browser to render the image ?!

if you used any http request debugger tool like Fiddler to analyze the request and response, you will find that your browser make an http request to your image URL and the server replies with an http response containing in one of the response headers a key named “Content-Type” with value “image/jpeg” then at the end of the response you will find the image bytes data so the browser recognize that this bytes data are for an image and that the image format is jpeg so it renders the image.

So this is great to know!! but how this help me in displaying my image, I already have the byte data but I don’t know how to send my image bytes data to the browser and how to tell the browser that this bytes array are for an image?

Use Generic Handler

The solution for that is to make the image src to a “URL” that can simulate what have done with the image source above. A URL that can reply to the browser with http response containing my image bytes and with the content type of the response as image. “Generic Handler” is a robust solution for this as generic handlers can receive browser http requests and it can respond to the browser with http response and it can control data returned in the response and can control the response type.

How to use Generic Handler ?

So what you need to do, is create a Generic Handler (.ashx) and name it ImageProvider.ashx so we find the following code auto generated ( if you are using visual studio ).

using System.Web;

 

namespace ImageUtil

{

    publicclassImageProvider : IHttpHandler

    {

        publicvoid ProcessRequest(HttpContext context)

        {

            context.Response.ContentType = “text/plain”;

            context.Response.Write(“Hello World”);

        }

        publicbool IsReusable

        {

            get {

                returnfalse;

            }

        }

    }

}

So what this code do ?! You will find that the generated class, handles the “IHttpHandler” interface which means that this class can handle an http request and it can return an http response and from the code above we can see that we have access to the HttpContext object which contain the Request property which allow us to get any information we need from the request and also it contains a Response property which allow us to edit in the response that will return to the browser.

As you can see in the “ProcessRequest()” function, it set the response content type to text and specifying the text type as plain text the it writes the “Hello World” string on the response, Now the browser can determine the type of data in the response and also it can determine how to render the response data.

Next we need to update our ImageProvider.ashx handler to return the image bytes and change the content type of the response.

using System.Web;

 

namespace ImageUtil

{

    publicclassImageProvider : IHttpHandler

    {

        publicvoid ProcessRequest(HttpContext context)

        {

            context.Response.ContentType = “image/jpeg”;

 

            context.Response.BinaryWrite(GetImageByteArray());

        }

 

        privatebyte[] GetImageByteArray()

        {

            //Return your image byte array.

        }

        publicbool IsReusable

        {

            get

            {

                returnfalse;

            }

        }

 

    }

}

Now after I have updated the code by setting the ContentType to “image/jpeg” the browser can detect that the byte data that will be in the response are for an image and it’s format is “.jpeg” ( you can set the format based on the actual format of the image).

Next, I call the BinaryWrite() function to write the image byte array on the response. Now, you can test your http handler from the browser by calling the handler URL you will see the image rendered. Try commenting the line that change the content type and run the handler URL again and you will find the browser returning the image bytes as a string (This is because the default content type is “text/html”)

Use the Handler as the image source

The final step to see the image on the browser is to change the <img> tag “src” attribute to be the url of the generic handler like “<img src=”ImageProvider.aspx”/>.

Conclusion:

1. Byte array can be displayed as an image on the browser using the generic handlers.

2. The generic handlers can handle user request and return a customized http response based on your requirement.

3. ContentType property of the response can change the behavior of the browser rendering of the response data.

Leave a comment