如何解决GDI +和内存不足的通用错误

时间:2018-10-14 05:25:07

标签: c# memory gdi

在C#中,我启动一个线程,该线程查找,裁剪并将某些单元格保存在图片中。但是在运行时会抛出异常:

C# Out of memory

这是我的代码:

Global.ThreadManager.StartThread(a =>
            {
                try
                {
                    System.Drawing.Bitmap croppedBitmap = new System.Drawing.Bitmap(this.Path + "image.jpg");
                    croppedBitmap = croppedBitmap.Clone(
                    new System.Drawing.Rectangle(
                        Convert.ToInt32(xCenter - width),
                        Convert.ToInt32(yCenter - width),
                        width * 2,
                        width * 2),
                        System.Drawing.Imaging.PixelFormat.DontCare
                    );
                    if (!File.Exists(Path + "MorphologySperms"))
                    {
                        Directory.CreateDirectory(Path + "MorphologySperms");
                    }
                    croppedBitmap.Save(Path + "Sperms\\" + "sperm_" + i.ToString() + ".jpg");
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message);
                };
            });

1 个答案:

答案 0 :(得分:0)

需要来处理您的图像,您不能依靠垃圾收集器及时找到这些图像并释放不受管理的 GDI 资源,这是一条路例外

已修复

using (var image = new System.Drawing.Bitmap(this.Path + "image.jpg"))
{
   using (var croppedBitmap = image.Clone(new Rectangle((int)xCenter - width, (int)yCenter - width, width * 2, width * 2), PixelFormat.DontCare))
   {
      // not sure what you are doing here, though it doesnt make sense
      if (!File.Exists(Path + "MorphologySperms"))
      {
         // why are you creating a directory and not using it
         Directory.CreateDirectory(Path + "MorphologySperms");
      }

      // use Path.Combine
      var somePath = Path.Combine(path, "Sperms");
      croppedBitmap.Save( Path.Combine(somePath, $"sperm_{I}.jpg"));
   }
}

它也极具争议,并且怀疑会像这样使用clone