如何调试误导GDI OutOfMemory异常?

问题描述:

我有哪些改变一个位图的功能。这是我简单地从另一个项目复制它这样的面包和黄油操作:

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;
}



不过,我一直在图形G故障排除OutOfMemory异常= Graphics.FromImage(调整)

我知道的是,的当谈到GDI,内存​​不足异常通常掩盖了其他问题的。我也很清楚,我想调整图片的大小并不大,而且(据我所知),因为它们离开当前范围GC应该没有问题收集实例。

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;
        }
    }
}



但现在我越来越

我生病的;对 resized.SetResolution(orig.Horizo​​ntalResolution,orig.VerticalResolution)InvalidOperation异常在黑暗中四处。是否有麻烦拍摄这些讨厌的GDI操作的更好的办法?

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

Graphics.FromImage 方法定义:

如果图像具有索引像素格式,此方法将引发与消息的异常,A

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."

虽然你例外,实在是误导性的,你想执行不受支持的操作。它看起来像你需要调整这个位图作为原始内存块,而不是GDI +位图。

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.