c#only Second Bitmap.Save产生GDI +异常中发生的一般错误

时间:2016-12-19 10:32:27

标签: c# bitmap gdi+ gdi

我使用以下代码比较两个图像并保存结果。 在第一次运行中,我成功创建并保存了结果图像, 但是在第二次运行中我得到以下异常:

An exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll but was not handled in user code

Additional information: A generic error occurred in GDI+.

代码:

MagickImage magickBaseImg = new MagickImage(new Bitmap(baseImageFileName));
MagickImage magickTargetImg = new MagickImage(new Bitmap(targetImageFileName));

var diffImg = new MagickImage();
magickBaseImg.Compare(magickTargetImg, ErrorMetric.RootMeanSquared, diffImg, Channels.Red);

Bitmap ImgToSave = diffImg.ToBitmap();

DateTime currentTime = DateTime.Now;
String differencesImageSavingPath = @"C:\test\DiffImage" + currentTime.ToString("ddMMyyyyHHmm") + ".bmp";
**ImgToSave.Save(differencesImageSavingPath, System.Drawing.Imaging.ImageFormat.Bmp);**

differencesImageFileName = differencesImageSavingPath;
DiffrenceImage.Source = new BitmapImage(new Uri(differencesImageFileName));

用**标记的行是在第二次运行中抛出异常的行。 已经阅读并尝试使用“using”和.dispose修复它,如下所示: A Generic error occurred in GDI+ in Bitmap.Save method 和这里: A generic error occurred in GDI+, JPEG Image to MemoryStream

但它没有用。

例如,以下代码也不起作用:

MagickImage magickBaseImg = new MagickImage(new Bitmap(baseImageFileName));
MagickImage magickTargetImg = new MagickImage(new Bitmap(targetImageFileName));

var diffImg = new MagickImage();
magickBaseImg.Compare(magickTargetImg, ErrorMetric.RootMeanSquared, diffImg, Channels.Red);

Bitmap ImgToSave = diffImg.ToBitmap();

DateTime currentTime = DateTime.Now;
String differencesImageSavingPath = @"C:\test\DiffImage" + currentTime.ToString("ddMMyyyyHHmm") + ".bmp";

using (var tempImg = new Bitmap(ImgToSave)) {
    tempImg.Save(differencesImageSavingPath, System.Drawing.Imaging.ImageFormat.Bmp);
}

differencesImageFileName = differencesImageSavingPath;
DiffrenceImage.Source = new BitmapImage(new Uri(differencesImageFileName));

1 个答案:

答案 0 :(得分:1)

我不确定为什么保存位图失败但不需要使其成为位图.Magick.NET库支持读写BMP图像。以下是如何更改代码的示例:

using (MagickImage magickBaseImg = new MagickImage(baseImageFileName))
using (MagickImage magickTargetImg = new MagickImage(targetImageFileName))
{
  using (var diffImg = new MagickImage())
  {
    magickBaseImg.Compare(magickTargetImg, ErrorMetric.RootMeanSquared, diffImg, Channels.Red);

    DateTime currentTime = DateTime.Now;
    string differencesImageSavingPath = @"C:\test\DiffImage" + currentTime.ToString("ddMMyyyyHHmm") + ".bmp";
    diffImg.Save(differencesImageSavingPath);

    differencesImageFileName = differencesImageSavingPath;
    DiffrenceImage.Source = new BitmapImage(new Uri(differencesImageFileName));
  }
}