.NET Bitmap.Clone() throws OutOfMemoryException

2

Why does the following simple piece of code (bitmap.Clone) throw an OutOfMemoryException?

        List<Bitmap> bitmapList = new List<Bitmap>();
        try
        {
            for (int i = 0; i < 1000; ++i)
            {
                using (Bitmap bitmap = new Bitmap(@"C:\temp\test.gif"))
                //using (Bitmap bitmap = new Bitmap(bitmap2))
                {
                    Bitmap clonedBitmap = bitmap.Clone(new Rectangle(0, 0, bitmap.Width, bitmap.Height), PixelFormat.Format8bppIndexed);
                    bitmapList.Add(clonedBitmap);
                    Debug.WriteLine("round " + i);
                }
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
        }
        finally
        {
            foreach (Bitmap bitmap in bitmapList)
            {
                bitmap.Dispose();
            }
        }

The exception is first thrown around round 95 (sometimes round 94 or 96), so the code works quite a few times before failing. The original GIF image is not very big so I cannot believe it is a real out of memory condition. I know that GDI+ maps many error conditions to OutOfMemoryException but what is the real underlying cause?

If I uncomment the second using line and change the file bitmap name to bitmap2, i.e. I create a new temporary bitmap which I then clone then the code works ok. Why?

                using (Bitmap bitmap2 = new Bitmap(@"C:\temp\test.gif"))
                using (Bitmap bitmap = new Bitmap(bitmap2))
                {

The HResult in the exception is 0x8007000e which according to Microsoft documentation can mean out of memory condition among many other things. Maybe some native resource problem but why should it manifest like this and be corrected by making an extra bitmap?

The cause is not the GIF image format either, I have tried with JPG and PNG images and the same problem appears.

My real purpose is to convert 24-bit RGB bitmaps to indexed 8-bit bitmaps. The resulting image from Clone is not very high quality though. Anybody know some better quality way to convert to 8-bit indexed bitmap or do I have to do it all myself from scratch including palette quantization?

c#
bitmap
asked on Stack Overflow Mar 19, 2016 by aku

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0