2017-05-16 41 views
0

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

这是我上传的代码上点击:

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); 

,然后我得到一个错误:

A generic error occurred in GDI+

回答

1

如果您已阅读MSDN Image.FromStream的文档,您应该已经注意到了th是:

Remarks You must keep the stream open for the lifetime of the Image. The stream is reset to zero if this method is called successively with the same stream.

您的问题是Image.FromStream将完成后您的MemoryStream将布置。

UPDATE
以下是您可以如何操作的示例。我是从加载图像文件,所以你必须改变我的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中保持加载直到表单没有关闭。在关闭窗体的事件之后,您必须关闭并处理您的MemoryStream。

+0

你能引导我如何将图像永远保存在那里?谢谢 – Rin

+0

@Rin我已经添加了示例如何加载图像按钮单击,以便图像保持加载,直到表单不关闭 –

+0

我认为这就是你之前已经有的东西:OI想知道如何我可以永远保持IMG后我关闭表格并打开它,以便它仍然存在。 – Rin

相关问题