简体   繁体   English

GDI +在位图上出现C#通用错误

[英]C# Generic Error with GDI+ on Bitmap.Save

public void EditAndSave(String fileName) {
    Bitmap b = new Bitmap(fileName);
    /**
    * Edit bitmap b... draw stuff on it...
    **/
    b.Save(fileName); //<---------Error right here
    b.Dispose();
}

My code is similar to the above code. 我的代码类似于上面的代码。 When i try to save the file i just opened, it won't work. 当我尝试保存刚刚打开的文件时,它将无法工作。 When i try saving it with a different path, it works fine. 当我尝试使用其他路径保存它时,它工作正常。 Could it be that the file is already open in my program so it cannot be written to? 可能是该文件已在我的程序中打开,因此无法写入? I'm very confused. 我很困惑

You are correct in that it is locked by your program and therefore you can't write to it. 您是正确的,因为它已被程序锁定,因此无法对其进行写入。 It's explained on the msdn-page for the Bitmap class (http://msdn.microsoft.com/en-us/library/3135s427.aspx). 在Bitmap类的msdn页上对此进行了说明(http://msdn.microsoft.com/zh-cn/library/3135s427.aspx)。

One way around this (from the top of my head, might be easier ways though) would be to cache image in a memorystream first and load it from there thus being able to close the file lock. 解决这个问题的一种方法(从我的头顶开始,也许是更简单的方法)将是先将图像缓存在内存流中,然后从那里加载它,从而能够关闭文件锁。

    static void Main(string[] args)
    {
        MemoryStream ms = new MemoryStream();
        using(FileStream fs = new FileStream(@"I:\tmp.jpg", FileMode.Open))
        {
            byte[] buffer = new byte[fs.Length];
            fs.Read(buffer, 0, buffer.Length);
            ms.Write(buffer, 0, buffer.Length);
        }

        Bitmap bitmap = new Bitmap(ms);

        // do stuff

        bitmap.Save(@"I:\tmp.jpg");
    }

I've not been in exactly the same situation as you, but I have had problems with open image files being kept open. 我和您的处境不完全相同,但是我一直无法打开打开的图像文件。

One suggestion is that you load the image into memory using the BitmapCacheOption.OnLoad , see my answer to this post: Locked resources (image files) management . 一个建议是您使用BitmapCacheOption.OnLoad将图像加载到内存中,请参阅我对本文的回答: 锁定资源(图像文件)管理

Then, after editing, that image can be saved to the the same file using a FileStream, that is described for example here: Save BitmapImage to File . 然后,在编辑之后,可以使用FileStream将图像保存到相同的文件,例如在此处进行描述: 将BitmapImage保存到File

I'm not sure it is the easiest or most elegant way, but I guess it should work for you. 我不确定这是最简单或最优雅的方法,但我想它应该对您有用。

Indeed there may be many reasons for seeing this exception. 确实,看到此异常可能有很多原因。

Note that if you're using PixelFormat.Format16bppGrayScale , it's not supported in GDI+ and fails in the way shown. 请注意,如果您使用的是PixelFormat.Format16bppGrayScale ,则GDI +不支持它,并且会以所示方式失败。 It seems the only workaround for using proper 16-bit gray scale is to use the newer System.Windows.Media namespace from WPF. 似乎使用正确的16位灰度的唯一解决方法是使用WPF中更新的System.Windows.Media命名空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM