C#位图/图形内存不足 [英] C# Bitmap/Graphics Out of Memory

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

问题描述

我正在尝试对整个屏幕进行快照以读取像素值.其实我正在做的没有任何问题.但是在精确拍摄了214个快照之后,我的内存不足异常了.

I'm trying to take a snapshot of the whole screen for reading pixel values. Actually i'm doing it without any problem. But after exactly 214 snapshots, i'm getting out of memory exception.

Bitmap ScreenShot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
  Screen.PrimaryScreen.Bounds.Height);

public Bitmap TakeSnapshot()
{
    Graphics graphic = null;
    Rectangle rect = new Rectangle(0, 0, Screen.PrimaryScreen.Bounds.Width,
      Screen.PrimaryScreen.Bounds.Height);

    using (graphic = Graphics.FromImage(ScreenShot))
    {
        graphic.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 
            0, 0, 
            ScreenShot.Size, 
            CopyPixelOperation.SourceCopy);
    }

    return ScreenShot.Clone(rect,System.Drawing.Imaging.PixelFormat.Format32bppArgb);
}

我将此方法与计时器配合使用

I'm using this method with timer

Bitmap bmp = TakeSnapshot();
        var c = bmp.GetPixel(0,0);

它给出了无效的参数异常.我用使用"解决了.但是现在我被这个例外困住了.

It was giving invalid parameter exception. I solved it with "using". But now i'm stuck on this exception.

推荐答案

处理完一次性资源后,您需要对其进行处置. Bitmap类实现了IDisposable-因此它是一次性资源.正确的模式代替了

You need to dispose disposable resources once you're done working with them. Bitmap class implements IDisposable - so it is disposable resource. Correct pattern is instead of

Bitmap bmp = TakeSnapshot();
var c = bmp.GetPixel(0,0);

类似

Bitmap bmp = null;
try
{
  bmp = TakeSnapshot();
  var c = bmp.GetPixel(0,0);
  // any more work with bmp
}
finally
{
  if (bmp != null)
  {
    bmp.Dipose();    
  }
}

或简写形式(最好):

using(Bitmap bmp = TakeSnapshot())
{
  var c = bmp.GetPixel(0,0);
  // any more work with bmp
}

参考:使用实现IDisposable的对象

修改

您可以轻松模拟问题:

public class TestDispose : IDisposable
{
    private IntPtr m_Chunk;
    private int m_Counter;
    private static int s_Counter;

    public TestDispose()
    {
        m_Counter = s_Counter++;
        // get 256 MB
        m_Chunk = Marshal.AllocHGlobal(1024 * 1024 * 256);
        Debug.WriteLine("TestDispose {0} constructor called.", m_Counter);
    }

    public void Dispose()
    {
        Debug.WriteLine("TestDispose {0} dispose called.", m_Counter);
        Marshal.FreeHGlobal(m_Chunk);
        m_Chunk = IntPtr.Zero;
    }
}

class Program
{
    static void Main(string[] args)
    {
        for(var i = 0; i < 1000; i ++)
        {
            var foo = new TestDispose();
        }
        Console.WriteLine("Press any key to end...");
        Console.In.ReadLine();
    }
}

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

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