In this article I will explain with an example, how to display BYTE Array i.e. binary data as image without using Generic Handler in ASP.Net using C# and VB.Net.
 
 

HTML Markup

The following HTML Markup consists of:
FileUpload – For selecting Image.
Button – For uploading selected Image.
The Button has been assigned with an OnClick event handler.
 
Image – For displaying uploaded image file.
The Visible property of the Image control is set to FALSE.
<asp:FileUpload ID="fuUpload" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="OnUpload" />
<hr />
<asp:Image ID="Image1" Visible="false" runat="server" Height="100" Width="100" />
 
 

Namespaces

You will need to import the following namespace.
C#
using System.IO;
 
VB.Net
Imports System.IO
 
 

Displaying Byte Array as Image in C# and VB.Net

When Upload button is clicked, first the input stream is read using InputStream property of the Stream class.
The BinaryReader class object is created which accepts Stream class object as parameter.
Then, the bytes of the uploaded image is read using ReadBytes method of the BinaryReader class and stored as BYTE Array.
The BYTE Array is converted to BASE64 string using ToBASE64String method and set to the ImageUrl property of the Image control.
Finally, the Visible property of Image control is set to TRUE and the Image will be displayed.
C#
protected void OnUpload(object sender, EventArgs e)
{
    using (Stream fs = fuUpload.PostedFile.InputStream)
    {
        using (BinaryReader br = new BinaryReader(fs))
        {
            byte[] bytes = br.ReadBytes((Int32)fs.Length);
            string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
            Image1.ImageUrl = "data:image/png;base64," + base64String;
            Image1.Visible = true;
        }
    }
}
 
VB.Net
Protected Sub OnUpload(ByVal sender As Object, ByVal e As EventArgs)
    Using fs As Stream = fuUpload.PostedFile.InputStream
        Using br As BinaryReader = New BinaryReader(fs)
            Dim bytes As Byte() = br.ReadBytes(CType(fs.Length, Int32))
            Dim base64String As String = Convert.ToBase64String(bytes, 0, bytes.Length)
            Image1.ImageUrl = "data:image/png;base64," & base64String
            Image1.Visible = True
        End Using
    End Using
End Sub
 
 

Screenshot

Display Byte Array as Image without using Generic Handler in ASP.Net
 
 

Demo

 
 

Downloads