How can I debug misleading GDI OutOfMemory exceptions?

我怕爱的太早我们不能终老 提交于 2019-12-08 04:03:38

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!