C# 覆盖现有图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8905714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:05:30  来源:igfitidea点击:

Overwrite Existing Image

c#imagebitmap

提问by Ozarraga_AB

I have this code

我有这个代码

    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();
    }

i already have an image t.jpgat my drive "c:\".
i wanted to replace it with a new image every time my program runs. but a GDI+ error shows up
how could i fix it?

我已经在我的驱动器"c:\" 上有一个图像t.jpg。 每次我的程序运行时,我都想用新图像替换它。但是出现了 GDI+ 错误, 我该如何解决?

采纳答案by Chuck Norris

You must remove your image if that is already exists.

如果已经存在,您必须删除您的图像。

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();
    }

回答by Adrian Bhagat

I presume you earlier loaded the c:\t.jpg image using the Image.Load method. If so, the Image object is holding an open file handle on the image file, which means that the file can't be overwritten.

我假设您之前使用 Image.Load 方法加载了 c:\t.jpg 图像。如果是这样,则 Image 对象在图像文件上持有一个打开的文件句柄,这意味着该文件不能被覆盖。

Instead of using Image.Load to get the original image, load it from a FileStream that you create and dispose of.

不是使用 Image.Load 来获取原始图像,而是从您创建和处理的 FileStream 加载它。

So, instead of

所以,而不是

Image image = Image.Load(@"c:\t.jpg");

do this:

做这个:

using(FileStream fs = new FileStream(@"c:\t.jpg", FileMode.Open))
{
    pictureBox.Image = Image.FromStream(fs);
    fs.Close();
}

The file handle has been released so overwriting the file with Bitmap.Save can succeed. The code you gave in your question should therefore work. There is no need to delete the original file or dispose of the image before saving.

文件句柄已被释放,因此使用 Bitmap.Save 覆盖文件可以成功。因此,您在问题中给出的代码应该可以工作。保存前无需删除原始文件或处理图像。