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

6

16

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.

Mikemikel answered 12/9, 2011 at 16:26 Comment(2)
Take a look at the answer to this similar question: #6987933Nisen
or this one: https://mcmap.net/q/197040/-what-39-s-the-best-way-to-display-an-image-from-a-sql-server-database-in-asp-net/76051Hydrops
A
42

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.

Archaeornis answered 12/9, 2011 at 17:0 Comment(4)
This is by far the easiest way to display binary images so far. BUT i found that this method works only with jpg images. I tried this with png images but it did not work.Trona
The method works on jpg and png as long as the browser supports it. It may be that your browser does not support it or their implementation is buggy.Archaeornis
Can you please explain data:image/png;base64 ?Trona
You are correct it was problem with IE, its working just fine in chrome. Any idea how can i make it work in IE?Trona
I
5

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;
}
Incapable answered 12/9, 2011 at 16:54 Comment(0)
J
1

In a generic handler (.ashx):

public class ImageHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        if(!string.IsNullOrEmpty(context.Request.QueryString["ImageId"]))
        {
           try
           {
                string ImageId = context.Request.QueryString["ImageId"].ToString(); 
                ImageDataModel idm = new ImageDataModel();
                byte[] ImageData = idm.getImageData(ImageId);
                context.Response.ContentType = "image/JPEG";
                context.Response.OutputStream.Write(ImageData, 0, ImageData.Length); 
            }
            catch(Exception ex){}
        }
    }

}
Justajustemilieu answered 12/9, 2011 at 16:53 Comment(0)
C
1
public Byte[] Ret_image(Int32 id)
{
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "select * from tbimage where imageid=@id";
    cmd.Connection = con;
    cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
    SqlDataReader dr = cmd.ExecuteReader();
    dr.Read();
    Byte[] ar = (Byte[])(dr[1]);
    dr.Close();
    cmd.Dispose();
    return ar;
}
Curfew answered 22/1, 2012 at 12:24 Comment(0)
C
1
protected void Button2_Click(object sender, EventArgs e)
{
    Byte[] ar = Ret_image(Convert.ToInt32(TextBox2.Text));
    String st = Server.MapPath("abc.jpg");
    FileStream fs = new FileStream(st, FileMode.Create, FileAccess.Write);
    fs.Write(ar, 0, ar.Length);
    fs.Close();
    Image1.ImageUrl = "abc.jpg";           
}

Use this event for the button click to retrieve image and call the Ret_Image method here.

Curfew answered 22/1, 2012 at 12:27 Comment(0)
C
0
SqlConnection con = new SqlConnection();
string _path;
Using SYstem.IO;
Using System.Data.SQLClient;

//convert Image to binary and save in DB

private void button1_Click(object sender, EventArgs e)
{
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        _path = openFileDialog1.FileName;
        InsertInSQL(_path);
    }
}

private void InsertInSQL(string _path)
{
    con.ConnectionString = Pic.Properties.Settings.Default.ConnectionS;
    string strQ = "insert into dbo.PicTBL(Pic)values(@p)";
    SqlCommand command = new SqlCommand(strQ,con);
    command.Parameters.AddWithValue("@p",ImageToBinary(_path));
    con.Open();
    command.ExecuteNonQuery();
    con.Close();
}      

public static byte[] ImageToBinary(string _path)
{
    FileStream fS = new FileStream(_path, FileMode.Open, FileAccess.Read);
    byte[] b = new byte[fS.Length];
    fS.Read(b, 0, (int)fS.Length);
    fS.Close();
    return b;
}

//Convert Binary to imge and save in a folder
private void button1_Click_1(object sender, EventArgs e)
{
    DataTable dt = Rimage();
    foreach (DataRow row in dt.Rows)
    {
        byte[] b = (byte[])row["Pic"];
        Image img = BinaryToImage(b);
        img.Save("D:\\NewFolder\\" + row["ID"].ToString() + ".jpg");
    }
}

private Image BinaryToImage(byte[] b)
{
    if (b == null) 
        return null;

    MemoryStream memStream = new MemoryStream();
    memStream.Write(b, 0, b.Length);

    return Image.FromStream(memStream);
}

private DataTable Rimage()
{
    con.ConnectionString = Pic.Properties.Settings.Default.ConnectionS;
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "select * from dbo.PicTBL";
    cmd.Connection = con;
    SqlDataAdapter adp = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    con.Open();
    adp.Fill(dt);

    return dt;
}
Contemporaneous answered 8/7, 2012 at 6:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.