覆盖现有图片

问题描述:

我有这样的代码覆盖现有图片

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://*.com/questions/1036115/c-sharp-gdi-overwriting-an-image-using-save-method-of-bitmap – 2012-01-18 05:45:47

+0

http://*.com/questions/ 838063 /覆盖图像文件位图 – 2012-01-18 05:46:31

如果该图像已存在,则必须删除图像。

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

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