如何在一个图片框中显示一个sql表中的字节数组图像?

时间:2013-05-18 23:26:38

标签: c#

我在sql表中有一个转换为字节数组的图像。当我从包含该表的dataGridView中单击记录时,如何在图片框中显示它?我需要实际的代码。谢谢。这个是我转换的代码:

private void button2_Click(object sender, EventArgs e)
{
    SqlConnection cn = new SqlConnection(@" Data Source=HOME-D2CADC8D4F\SQL;Initial Catalog=motociclete;Integrated Security=True");
    MemoryStream ms = new MemoryStream();
    pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

    byte[] pic_arr = new byte[ms.Length];
    ms.Position = 0;
    ms.Read(pic_arr, 0, pic_arr.Length);

    SqlCommand cmd = new SqlCommand("insert into motociclete(firma,model,poza,pret,anf,greutate,caprez,putere,garantie,stoc) values (@firma,@model,@poza,@pret,@anf,@greutate,@caprez,@putere,@garantie,@stoc)",cn);
    cmd.Parameters.AddWithValue("@firma", textBox3.Text);
    cmd.Parameters.AddWithValue("@model", textBox10.Text);
    cmd.Parameters.AddWithValue("@poza", pic_arr);
    cmd.Parameters.AddWithValue("@pret", textBox7.Text);
    cmd.Parameters.AddWithValue("@anf", textBox4.Text);
    cmd.Parameters.AddWithValue("@greutate", textBox9.Text);
    cmd.Parameters.AddWithValue("@caprez", textBox5.Text);
    cmd.Parameters.AddWithValue("@putere", textBox8.Text);
    cmd.Parameters.AddWithValue("@garantie", textBox6.Text);
    cmd.Parameters.AddWithValue("@stoc", textBox2.Text);

    cn.Open();

    try
    {
        int rez = cmd.ExecuteNonQuery();
        if (rez > 0)
        {
            MessageBox.Show("Adaugare reusita ");
        }
    }
    catch (Exception)
    {
        MessageBox.Show("Inregistrarea exista deja ");
    }
    finally
    {
        cn.Close();
        obj.loaddata();
        this.Close();
    }
}

1 个答案:

答案 0 :(得分:5)

假设picture是从数据库中提取的byte[]

byte[] picture = // read from db
PicBoxImage.Image = Image.FromStream(new MemoryStream(picture));                                
PicBoxImage.Refresh();