1

I have a function which resizes a bitmap. It's such a "bread and butter" operation that I simply copied it from another project:

private Bitmap ResizeBitmap(Bitmap orig)
{
    Bitmap resized = new Bitmap(this.Xsize, this.Ysize, PixelFormat.Format16bppGrayScale);
    resized.SetResolution(orig.HorizontalResolution, orig.VerticalResolution);
    using (Graphics g = Graphics.FromImage(resized))
    {
        g.DrawImage(orig, 0, 0, resized.Width, resized.Height);
    }
    return resized;
}

However, I kept getting OutOfMemory exceptions on Graphics g = Graphics.FromImage(resized).

I'm aware that, when it comes to GDI, OutOfMemory exceptions usually mask other problems. I'm also very aware that the image I'm trying to resize isn't large and that (as far as I'm aware) the GC should have no problem collecting instances as they leave the current scope.

Anyway, I've been playing around with it for a bit now and it currently looks like this:

private Bitmap ResizeBitmap(Bitmap orig)
{
    lock(orig)
    {
        using (Bitmap resized = new Bitmap(this.Xsize, this.Ysize, PixelFormat.Format16bppGrayScale))
        {
            resized.SetResolution(orig.HorizontalResolution, orig.VerticalResolution);
            using (Graphics g = Graphics.FromImage(resized))
            {
                g.DrawImage(orig, 0, 0, resized.Width, resized.Height);
            }
            return resized;
        }
    }
}

But now I'm getting an InvalidOperation exception on resized.SetResolution(orig.HorizontalResolution, orig.VerticalResolution);

I'm sick of poking around in the dark. Is there a better way to trouble shoot these pesky GDI operations?

Community
  • 1
  • 1
Tom Wright
  • 11,278
  • 15
  • 74
  • 148

1 Answers1

2

From Graphics.FromImage Method definition:

If the image has an indexed pixel format, this method throws an exception with the message, "A Graphics object cannot be created from an image that has an indexed pixel format."

Though exception you get is really misleading, you are trying to execute unsupported operation. It looks like you need to resize this bitmap as raw memory block, and not as GDI+ bitmap.

Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219
Alex F
  • 42,307
  • 41
  • 144
  • 212
  • Just checking - `Format16bppGrayScale` is considered an indexed pixel format? – Tom Wright Oct 02 '12 at 15:42
  • Yes, all grayscale images have actually indexed format, with grayscale palette (0,0,0), (1,1,1) ... Format16bppGrayScale is mentioned as unsupported in Graphics.FromImage MSDN topic. – Alex F Oct 02 '12 at 17:01
  • Thanks. This solves the immediate problem, but I'm going to leave the question open for a while as I'd like to hear about general debugging techniques. – Tom Wright Oct 03 '12 at 12:45