Noé Perracini
Noé Perracini

Reputation: 13

C# save image to file system, error in gdi+

I have a C# WPF application which cuts a image to the size I need it. The WPF window is used to put in a user ID to save the image into a database. When I test my application it works sometimes and sometimes i get a error in gdi+ on the line I save the image to the file system.

Here is my code:

public static void CutImage(Image image)
    {
        //create new image
        Bitmap source = new Bitmap(image);
        //cut image
        Bitmap cuttedImage = source.Clone(new System.Drawing.Rectangle(250, 0, 5550, 4000), source.PixelFormat);
        //copy bitmap to avoid "general error in gdi+"
        Bitmap copyImage = new Bitmap(cuttedImage.Width, cuttedImage.Height, PixelFormat.Format24bppRgb);
        Graphics g = Graphics.FromImage(copyImage);
        g.DrawImageUnscaled(cuttedImage, 0, 0);
        //dispose graphics object
        g.Dispose();
        //dispose image
        cuttedImage.Dispose();
        //save image to filesystem
        copyImage.Save(@"path\tmp.jpg", ImageFormat.Jpeg);
    }

        //get image
        Image i = Image.FromFile(path\image.jpg);
        //cut image
        CutImage(i);

I searched for a solution and somebody said I have to create a copy of the image I got from Image.FromFile(). But the error still happens sometimes. I tried it a few times and it seems to be random when it happens. The error is always on the Image.Save() line.

Does somebody know how to solve this problem or is there a alternative to Image.Save()?

Thanks for your help!

Upvotes: 0

Views: 877

Answers (1)

Enigmativity
Enigmativity

Reputation: 117175

You're creating so many bitmaps and you're not disposing them. Every single IDisposable must be explicitly disposed when you're finished with them.

Try this and see if the error goes away:

public static void CutImage(Image image)
{
    using (Bitmap source = new Bitmap(image))
    {
        using (Bitmap cuttedImage = source.Clone(new System.Drawing.Rectangle(250, 0, 5550, 4000), source.PixelFormat))
        {
            using (Bitmap copyImage = new Bitmap(cuttedImage.Width, cuttedImage.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
            {
                using (Graphics g = Graphics.FromImage(copyImage))
                {
                    g.DrawImageUnscaled(cuttedImage, 0, 0);
                    copyImage.Save(@"path\tmp.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }
        }
    }
}

Upvotes: 1

Related Questions