2017-05-16 42 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

相關問題