Mohammad Adib
Mohammad Adib

Reputation: 818

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.

Upvotes: 1

Views: 5923

Answers (3)

Drew Noakes
Drew Noakes

Reputation: 311285

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. It seems the only workaround for using proper 16-bit gray scale is to use the newer System.Windows.Media namespace from WPF.

Upvotes: 0

Karl-Johan Sj&#246;gren
Karl-Johan Sj&#246;gren

Reputation: 17622

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).

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

Upvotes: 2

ekholm
ekholm

Reputation: 2573

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.

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.

I'm not sure it is the easiest or most elegant way, but I guess it should work for you.

Upvotes: 0

Related Questions