Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from binary data to an image control in ASP.NET

I have binary data of an image in my database, and I want to display it in an image control in ASP.NET. How? If it is impossible, please find another way to save it in the database and display it in an image control.

like image 252
kartal Avatar asked Sep 12 '11 16:09

kartal


2 Answers

Create a regular HTML img element like so:

<img runat="server" id="image" />

And in code behind do this:

image.src = "data:image/png;base64," + Convert.ToBase64String(imageBytes);

Where imageBytes is a byte[].

You are done. The image will be displayed.

like image 51
Icarus Avatar answered Oct 18 '22 17:10

Icarus


Most likely the image is being stored as a byte array in the database. If so, then you can use this:

public static System.Drawing.Image ByteArrayToImage(byte[] bArray)
{
    if (bArray == null)
        return null;

    System.Drawing.Image newImage;

    try
    {
        using (MemoryStream ms = new MemoryStream(bArray, 0, bArray.Length))
        {
            ms.Write(bArray, 0, bArray.Length);
            newImage = System.Drawing.Image.FromStream(ms, true);
        }
    }
    catch (Exception ex)
    {
        newImage = null;

        //Log an error here
    }

    return newImage;
}
like image 31
Jon Raynor Avatar answered Oct 18 '22 18:10

Jon Raynor