即使我关闭窗口,如何保持img保存到PictureBox

时间:2017-05-16 19:10:09

标签: c# visual-studio

从数据库上传图片后,有人可以帮我了解如何将图片保存在图片框中。我的问题是一切正常,但关闭窗口后图像消失了,我需要点击按钮显示它,如何在图片上传后自动显示图片?

这是我点击上传的代码:

private void button2_Click(object sender, EventArgs e)
{
    //DB Connection string
    string strConn;
    strConn = "Data Source=MARINCHI\\SQLEXPRESS;Initial Catalog=login1;Integrated Security=True";
    try
    {
        SqlConnection conn = new SqlConnection(strConn);
        conn.Open();

        //Retriver img from DB into Dataset
        SqlCommand sqlCmd = new SqlCommand("SELECT id, image FROM user2 ORDER BY id", conn);
        SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCmd);
        DataSet ds = new DataSet();
        sqlDA.Fill(ds, "image");
        int c = ds.Tables["image"].Rows.Count;

        if (c > 0)
        {
            Byte[] bytIMGDATA = new Byte[0];
            bytIMGDATA = (Byte[])(ds.Tables["image"].Rows[c - 1]["image"]);
            using (MemoryStream stmIMGDATA = new MemoryStream(bytIMGDATA))
            {                 
            pictureBox1.Image = Image.FromStream(stmIMGDATA);


            }
            MessageBox.Show("File read from database succesfully");
        }

    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

}

此外,我尝试在链接下方添加pictureBox1.Image = Image.FromStream(stmIMGDATA);

pictureBox1.Image.Save(stmIMGDATA, pictureBox1.Image.RawFormat); 

然后我收到错误:

  

GDI +中发生了一般错误

1 个答案:

答案 0 :(得分:1)

如果您已阅读Image.FromStream的MSDN文档,那么您应该注意到这一点:

  

<强>说明   您必须在图像的生命周期内保持流打开。   如果连续调用此方法,则流将重置为零   相同的流。

您的问题是MemoryStream将在Image.FromStream完成后处理。

UPDATE
以下是如何做到这一点的示例。我正在从File加载图像,所以你必须将我的FileStream更改为MemoryStream以适合你的情况:

public partial class Form1 : Form
{
    private MemoryStream _memoryStream = new MemoryStream();
    public Form1()
    {
        InitializeComponent();

        string picturePath = @"c:\Users\IIG\Desktop\download.png";
        using (var fileStream = File.OpenRead(picturePath))
        {
            byte[] data = new byte[fileStream.Length];
            fileStream.Read(data, 0, data.Length);
            _memoryStream = new MemoryStream(data);
            pictureBox1.Image = Image.FromStream(_memoryStream);
        }
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        try
        {
            _memoryStream.Close();
            _memoryStream.Dispose();
        }
        catch (Exception exc)
        {
            //do some exception handling
        } 
    }
}

在此示例中,图像将保持加载到pictureBox中,直到表单未关闭。在关闭Form的事件时,你必须关闭并处理你的MemoryStream。