2012-01-18 169 views
21

我有這樣的代碼覆蓋現有圖片

private void saveImage() 
    { 
     Bitmap bmp1 = new Bitmap(pictureBox.Image); 
     bmp1.Save("c:\\t.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); 
     // Dispose of the image files. 
     bmp1.Dispose(); 
    } 

我已經有一個形象t.jpg在我的硬盤「C:\」
我想在每次運行程序時用新圖像替換它。但一個GDI +錯誤顯示
我該如何解決它?

+0

可能的重複http://stackoverflow.com/questions/1036115/c-sharp-gdi-overwriting-an-image-using-save-method-of-bitmap – 2012-01-18 05:45:47

+0

http://stackoverflow.com/questions/ 838063 /覆蓋圖像文件位圖 – 2012-01-18 05:46:31

回答

30

如果該圖像已存在,則必須刪除圖像。

private void saveImage() 
    { 
     Bitmap bmp1 = new Bitmap(pictureBox.Image); 

     if(System.IO.File.Exists("c:\\t.jpg")) 
       System.IO.File.Delete("c:\\t.jpg"); 

     bmp1.Save("c:\\t.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); 
     // Dispose of the image files. 
     bmp1.Dispose(); 
    } 
+0

這應該解決我的問題,但在System.IO.File.Delete出現新的錯誤。它說,*進程無法訪問文件,因爲它正在被另一個進程使用* – 2012-01-18 05:58:56

+0

你有任何其他部分的代碼與該文件一起工作嗎? – 2012-01-18 06:09:32

+0

這一個'img1 =新的位圖(@「c:\\ t.jpg」,true);'。這從程序開始運行 – 2012-01-18 06:21:57

0
private void saveImage(Image file, string filename){ 
    try 
    {  
     if(Directory.Exists("filepath"+filename)) 
     { 
      file.Dispose(); 
     } 
     else 
     { 
      Directory.CreateDirectory("filepath"+filename); 
      file.Save("filepath" + filename, Imageformat.Jpeg); 
     } 
    } 
    finally 
    { 
     file.Dispose(); 
    }   
} 

這一個爲我工作。

+1

這不會取代現有的文件!此外,它正在檢查/創建目錄而不是文件,並且應該使用Path.Combine完成組合路徑... – Ronald 2017-08-10 09:07:32