C# 创建位图时内存不足 [英] C# Out of Memory when Creating Bitmap

查看:122
本文介绍了C# 创建位图时内存不足的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个应用程序(Windows 窗体),允许用户根据他们选择的位置(拖动以选择区域)截取屏幕截图.我想添加一个放大的小预览窗格",以便用户可以更精确地选择他们想要的区域(更大的像素).在 mousemove 事件中,我有以下代码...

I'm creating an application (Windows Form) that allows the user to take a screenshot based on the locations they choose (drag to select area). I wanted to add a little "preview pane" thats zoomed in so the user can select the area they want more precisely (larger pixels). On a mousemove event i have a the following code...

private void falseDesktop_MouseMove(object sender, MouseEventArgs e)
    {
        zoomBox.Image = showZoomBox(e.Location);
        zoomBox.Invalidate();
        bmpCrop.Dispose();
    }

private Image showZoomBox(Point curLocation)
    {
        Point start = new Point(curLocation.X - 50, curLocation.Y - 50);
        Size size = new Size(100, 90);
        Rectangle rect = new Rectangle(start, size);
        Image selection = cropImage(falseDesktop.Image, rect);
        return selection;
    }

private static Bitmap bmpCrop;
private static Image cropImage(Image img, Rectangle cropArea)
    {
        if (cropArea.Width != 0 && cropArea.Height != 0)
        {
            Bitmap bmpImage = new Bitmap(img);
            bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
            bmpImage.Dispose();
            return (Image)(bmpCrop);
        }
        return null;
    }

失败并出现内存不足异常的行是:

The line that fails and has the Out of Memory exception is:

bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);

基本上它的作用是在鼠标指针周围取一个 100x90 的矩形并将其拉入缩放框,这是一个图片框控件.但是,在此过程中,我收到内存不足错误.我在这里做错了什么?

Basically what this does is it takes a 100x90 rectangle around the mouse pointer and pulls that into the zoomBox, which is a picturebox control. However, in the process, i get an Out Of Memory error. What is it that i am doing incorrectly here?

感谢您的帮助.

推荐答案

C# 成像中的内存不足,通常是错误的 rect 或 point 的标志 - 有点红鲱鱼.我敢打赌 start 在发生错误或 Size.Hight + Y 或 Size.Width + X 大于图像的高度或宽度时具有 负 X 或 Y.

Out of memory in C# imaging, is usually sign of wrong rect or point - a bit of red herring. I bet start has negative X or Y when error happens or the Size.Hight + Y or Size.Width + X is bigger than Hight or width of the image.

这篇关于C# 创建位图时内存不足的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆