2015-11-05 76 views
0

我在C#表單上顯示圖像。當用戶點擊「保存圖像」按鈕時,彈出一個Visual Basic輸入框。我正在嘗試添加功能到我的表單中,當用戶通過可視化基本輸入框輸入圖像名稱時,用戶可以保存圖像。C#:將圖像保存到Documents文件夾時出錯

首先,我加入這個代碼,

private void save_image(object sender, EventArgs e) 
    { 
     String picname; 
     picname = Interaction.InputBox("Please enter a name for your Image");    
     pictureBit.Save("C:\\"+picname+".Png");      
     MessageBox.Show(picname +" saved in Documents folder"); 
    } 

然而,當我運行該程序,然後點擊保存按鈕,它給出了這樣的例外:「類型‘System.Runtime.InteropServices.ExternalException’未處理的異常發生在System.Drawing.dll程序」

然後我添加到代碼一些改變,使它看起來像這樣,

private void save_image(object sender, EventArgs e) 
    { 

     SaveFileDialog savefile = new SaveFileDialog();    
     String picname;   
     picname = Interaction.InputBox("Please enter a name for your Image"); 
     savefile.FileName = picname + ".png"; 
     String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); 
     using (Stream s = File.Open(savefile.FileName, FileMode.Create)) 
     { 
      pictureBit.Save(s, ImageFormat.Png); 
     } 
     //pictureBit.Save("C:\\pic.Png");   
     MessageBox.Show(picname);         
    } 

當我運行這段代碼,它不給excep但它將圖像保存在我的c# - > bin-> debug文件夾中。我知道這可能不是實現它的理想方式,但我如何設置它的路徑,以便將圖像保存到文檔文件夾中。

+0

你不設置路徑 – BeardedMan

+0

如何設置路徑?這就是我不明白 – user5455438

+0

嘗試類似'savefile.FileName = string.Format(「{0} \\ {1} .png」,路徑,picname);' – BeardedMan

回答

1
String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); 
savefile.FileName = path + "\\" + picname + ".png"; 

工作其他例如與顯示對話框:

SaveFileDialog savefile = new SaveFileDialog(); 
String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); 

savefile.InitialDirectory = path; 
savefile.FileName = "picname"; 
savefile.Filter = "PNG images|*.png"; 
savefile.Title = "Save as..."; 
savefile.OverwritePrompt = true; 

if (savefile.ShowDialog() == DialogResult.OK) 
{ 
    Stream s = File.Open(savefile.FileName, FileMode.Create); 
    pictureBit.Save(s,ImageFormat.Png); 
    s.Close(); 
} 

其他保存例如:

if (savefile.ShowDialog() == DialogResult.OK) 
{ 
    pictureBit.Save(savefile.FileName,ImageFormat.Png); 
} 
+0

非常感謝你,它添加後代碼和一個小改動。它應該是兩個反斜槓而不是一個。 – user5455438

+0

沒錯。我的錯。 – c4pricorn

+0

當我決定保存圖像時,首先,我嘗試使用與第二個示例非常相似的圖像。然而,它給出了一個異常,說「System.Threading.ThreadStateException'類型的未處理的異常發生在System.Windows.Forms.dll」,我不明白如何解決,所以這就是爲什麼我嘗試了VB輸入框方法。你有什麼想法如何解決這個異常? – user5455438

相關問題