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?
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.
来源:https://stackoverflow.com/questions/12693276/how-can-i-debug-misleading-gdi-outofmemory-exceptions