Как решить общую ошибку в GDI + и нехватка памяти - PullRequest
0 голосов
/ 14 октября 2018

В 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 голосов
/ 14 октября 2018

Вам нужно для утилизации ваших изображений, вы не можете рассчитывать на сборщик мусора, чтобы найти их вовремя и освободить неуправляемые ресурсы GDI , это улица с односторонним движением кисключение

Также

Fixed

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 как это

...