c# - Aforge 内存使用

标签 c# memory-management memory-leaks aforge

我已经编写了一些需要处理大约 3000 张图像的 C# 代码,但是到第 500 张图像时,任务管理器显示该程序使用了 1.5GB 的内存。下面的功能似乎是罪魁祸首之一。我可以在这里做得更好吗?任何帮助或建议表示赞赏。谢谢。

   private void FixImage(ref Bitmap field)
    {
        //rotate 45 degrees
        RotateBilinear rot = new RotateBilinear(45);
        field = rot.Apply(field);               //Memory spikes 2mb here
        //crop out unwanted image space
        Crop crop = new Crop(new Rectangle(cropStartX, cropStartY, finalWidth, finalHeight));
        field = crop.Apply(field);              //Memory spikes 2mb here
        //correct background
        for (int i = 0; i < field.Width; i++)
        {
            for (int j = 0; j < field.Height; j++)
            {
                if (field.GetPixel(i, j).ToArgb() == Color.Black.ToArgb())
                    field.SetPixel(i, j, Color.White);
            }
        }                                  //Memory usuage increases 0.5mb by the end
    }

最佳答案

像这样更改代码时我可以减少内存

private void FixImage(ref Bitmap field)
{
    //rotate 45 degrees
    RotateBilinear rot = new RotateBilinear(45);
    var rotField = rot.Apply(field);               //Memory spikes 2mb here
    field.Dispose();
    //crop out unwanted image space
    Crop crop = new Crop(new Rectangle(cropStartX, cropStartY, finalWidth, finalHeight));
    var cropField = crop.Apply(rotField);              //Memory spikes 2mb here
    rotField.Dispose();
    //correct background
    for (int i = 0; i < cropField.Width; i++)
    {
        for (int j = 0; j < cropField.Height; j++)
        {
            if (cropField.GetPixel(i, j).ToArgb() == Color.Black.ToArgb())
                cropField.SetPixel(i, j, Color.White);
        }
    }                                  //Memory usuage increases 0.5mb by the end
    field = cropField;
}

所以这似乎是一个好主意,立即释放该图像内存,而不是等到 GC 最终处理它。

关于c# - Aforge 内存使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8282597/

相关文章:

c# - 如何在文件中存储自定义结构的数组?

memory-management - mmap 是否连续分配堆内存?

memory-management - 一种具有垃圾收集和手动内存管理功能的编程语言

c++ - 函数返回的神秘段错误,不涉及指针或分配

c++ - 将指针传递给具有私有(private) *tors 的类是否危险?

c# - 从 WPF 应用程序显示 WinForm 对话框的性能问题

c# - 如何实现搜索?

c# - 将所有标记的字符串更改为另一个字符串

c - 获取包含动态分配内存的结构的大小

objective-c - 如何修复 SBJsonParser 实现文件中的内存泄漏?