从数据库到Windows窗体的映像

时间:2012-03-16 10:01:39

标签: .net sql-server winforms

private void button2_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection("Data Source=SYS12;Initial Catalog=Teju;Integrated Security=True");
    SqlCommand cmd = new SqlCommand("Select Picture from tblImgData where id= " + listBox1.SelectedValue + " ", con);
    con.Open();
    byte[] byteImg = (byte[])cmd.ExecuteScalar();
    string strfn = Convert.ToString(DateTime.Now.ToFileTime());
    FileStream fs = new FileStream(strfn, FileMode.CreateNew, FileAccess.Write);
    fs.Write(byteImg, 0, byteImg.Length-1);
    fs.Flush();
    fs.Close();
    pictureBox1.Image = Image.FromFile(strfn);
}

此代码显示错误为“Out of memory”。我可能做错了什么,或者我如何调试和解决这个问题?谢谢!

2 个答案:

答案 0 :(得分:2)

使用System.Drawing.Image类保存文件,然后直接将此图像分配到图片框。

检查一下:

private void button2_Click(object sender, EventArgs e)
{

    SqlConnection con = new SqlConnection("Data Source=SYS12;Initial Catalog=Teju;Integrated Security=True");
    SqlCommand cmd = new SqlCommand("Select Picture from tblImgData where id= " + listBox1.SelectedValue + " ", con);
    con.Open();
    byte[] byteImg = (byte[])cmd.ExecuteScalar();
    string strfn = Convert.ToString(DateTime.Now.ToFileTime());
   Stream stream = new MemoryStream(byteImg);
Image img = System.Drawing.Image.FromStream(stream);

img.Save(strfn , ImageFormat.Jpeg);
    pictureBox1.Image = img;
}

答案 1 :(得分:1)

不处理您的物品不会有帮助。使用try/finally块或using statement来自行清理。