2017-05-16 7 views
0

ピクチャボックスに画像をアップロードした後、画像ボックスに画像を保存する方法を教えてもらえますか?私の問題は、ウィンドウを閉じた後に画像が消える以外はすべて動作することです。ボタンをクリックすると表示されます。画像がアップロードされたらどのように画像ボックスに自動的に表示されますか?ウィンドウを閉じても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.Save(stmIMGDATA, pictureBox1.Image.RawFormat); 

pictureBox1.Image = Image.FromStream(stmIMGDATA);)下のリンクを追加しようとしましたし、私はエラーを取得:

A generic error occurred in GDI+

答えて

1

Image.FromStreamのMSDNドキュメントをお読みになりましたら、次のとおりです。

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が配置されるということです。

更新
これはどのように実行できるかを示したものです。あなたがあなたのケースに合わせてのMemoryStreamに自分のFileStreamを変更する必要がありますので、私は、ファイルからイメージをロードしたフォームが閉じなくなるまで、この例の画像で

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 
     } 
    } 
} 

は、ピクチャボックスにロードされたままになります。フォームの終了イベントでは、MemoryStreamを閉じて処分する必要があります。

+0

イメージを「永遠に」保存するにはどうすればいいですか?ありがとうございます – Rin

+0

@Rin私は例を追加しました画像をクリックしてボタンをクリックするとフォームが閉じないうちに画像がロードされたままになります –

+0

あなたが投稿した前に私がすでに持っていたことを思います:OIは、私はフォームを閉じてそれを開いています。 – Rin

関連する問題