ASP.NET - how to display image from binary - Asked By msakt on 29-May-12 08:06 AM

during insert i encrypt image into binary....now i want display image...how can i decrypt
Jitendra Faye replied to msakt on 29-May-12 08:17 AM
For this first read image from database and follow the same key which you have used for encryption.

try like this-

SqlConnection cn = new SqlConnection("constring");
        cn.Open();
        string strQuery = "Select * from EmpImage";
        SqlDataAdapter da = new SqlDataAdapter(strQuery, cn);
        DataSet ds = new DataSet();
        da.Fill(ds);

        byte[] b = new byte[0];
        b = (Byte[])(ds.Tables[0].Rows[0][1]);

        MemoryStream ms = new MemoryStream(b);

       pictureBox1.Image = Image.FromStream(ms);

dipa ahuja replied to msakt on 29-May-12 10:29 AM
Step 1: Add a handle in your website and write this code in ProcessRequest:
public void ProcessRequest (HttpContext context)
{
  SqlConnection con = new SqlConnection();
  con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
 
  // Create SQL Command
 
  SqlCommand cmd = new SqlCommand();
  cmd.CommandText = "Select pname,images from Photos where id =@id";
  cmd.CommandType = System.Data.CommandType.Text;
  cmd.Connection = con;
 
  SqlParameter ImageID = new SqlParameter("@id", System.Data.SqlDbType.Int);
  ImageID.Value = context.Request.QueryString["id"];
  cmd.Parameters.Add(ImageID);
  con.Open();
  SqlDataReader dReader = cmd.ExecuteReader();
  dReader.Read();
  context.Response.BinaryWrite((byte[])dReader["images"]);
  dReader.Close();
  con.Close();
}
 
Step 2: Add a Image Control in ItemTemplate:
 
<ItemTemplate>
  <asp:Image ID="Image1" runat="server"
ImageUrl='<%# "Handler.ashx?id=" + Eval("id")%>'/>
</ItemTemplate>
 
//display image from the database using handler
Image2.ImageUrl = "Handler.ashx?id=2";
 
 
 
 
Goniey N (Mr. G) replied to msakt on 30-May-12 12:59 AM
Try This Code :

public Image BinaryToImageConvert(byte[] binaryImageData)

{

     if (binaryImageData == null) return null;

 

     byte[] imageBytes = binaryImageData.ToArray();

     MemoryStream memStream = new MemoryStream();

     memStream.Write(imageBytes, 0, imageBytes.Length);

return Image.FromStream(memStream);

}

 

 

private void button1_Click(object sender, EventArgs e)

{

Image img = BinaryToImage(<<Pass Here Your Binary Data Which You Want To Convert In Image>>);

}


Hope this will helpful to you....