Sunday, July 7, 2013

retrived image from database saved as binary


This is how you can get array of byte from database

public static byte[] GetImage(string ImageId)
{ byte[] img = null;
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "your_store_procedure_returns_binary_Image";
cmd.Parameters.AddWithValue("@CODE", ImageId);
cmd.Connection = yourConnection();
SqlDataReader dr = null;
dr = cmd.ExecuteReader();
if (dr.Read())
{
    img = (byte[])dr[0];
}
dr.Close();
return img;//returns array of byte
}
on your handler.ashx
public void ProcessRequest(HttpContext context)
{
 context.Response.ContentType = "image/jpeg";
 Stream strm = new MemoryStream(GetImage(ID));
 long length = strm.Length;
 byte[] buffer = new byte[length];
 int byteSeq = strm.Read(buffer, 0, 2048);

 while (byteSeq > 0)
 {
       context.Response.OutputStream.Write(buffer, 0, byteSeq);
       byteSeq = strm.Read(buffer, 0, 2048);
  }
}
now set image url for your asp:image inside your gridview as follows
Image1.ImageUrl = "somthing.ashx?ID="+userImageID;
i hope you have unique id for your image to be visible. I hope you have all set now. Comments and query are well comed.

No comments: