1) Retrieve the image data from the database as an array of bytes.
2) Convert the bytes to an Image:
MemoryStream ms = new MemoryStream(bytes);
Image returnImage = Image.FromStream(ms);
3) Set the Image property of the Picture box to the converted data.
myPictureBox.Image = returnImage;
i tried .. but i got error.. guide me.. below my code
private void Form1_Load(object sender, EventArgs e)
{
cn.Open();
cmd=new SqlCommand("select * from img where id=6",cn);
cmd.Connection=cn;
dr=cmd.ExecuteReader();
byte bytes;
while (dr.Read())
{
double dble = Convert.ToDouble(dr[2].ToString());
bytes = Convert.ToByte(dble);
MemoryStream ms = new MemoryStream(bytes);
Image returnImage = Image.FromStream(ms);
pictureBox1.Image = returnImage;
}
cn.Close();
}
Don't retrieve the data as a double - a double is a floating point number occupying 8 bytes. And image (of any type) is going to be bigger than that!
You need to retrieve an array of bytes, not a single byte, so declare it as such.
In addition, don't use a loop there - since you are only using a single row, you only need an if statement.
BTW: Don't retrieve info from your database that you aren't going to use. In this case, it doesn't make a significant difference, but since you are storing images in the table, if you are not going to use them, don't retrieve them - it wastes bandwidth & memory and slows the program down, possibly significantly depending on where your SQL server is. And never use magic numbers with databases! If someone else comes along and re-orders the columns in your database, you code stops working and you don't know why! :laugh: Use names field access instead.
And remember - you are responsible for cleaning up after yourself! Dispose scarce connections or use a
using
block:
So:
private void Form1_Load(object sender, EventArgs e)
{
cn.Open();
using (cmd=new SqlCommand("SELECT myImage FROM img WHERE id=6",cn))
{
cmd.Connection=cn;
dr=cmd.ExecuteReader();
if (dr.Read())
{
byte[] bytes = (byte[]) dr["myImage"];
MemoryStream ms = new MemoryStream(bytes);
Image returnImage = Image.FromStream(ms);
pictureBox1.Image = returnImage;
}
}
cn.Close();
}