c# – 绘制图像时:System.Runtime.InteropServices.ExternalException:GDI中发生一般错误

前端之家收集整理的这篇文章主要介绍了c# – 绘制图像时:System.Runtime.InteropServices.ExternalException:GDI中发生一般错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个从Panel创建的全局Graphics对象.定期从磁盘拾取图像并使用Graphics.Draw Image()绘制到面板中.它工作正常的几次迭代,然后我得到以下有用的例外:
System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.
at System.Drawing.Graphics.CheckErrorStatus(Int32 status)
at System.Drawing.Graphics.DrawImage(Image image,Int32 x,Int32 y)
at System.Drawing.Graphics.DrawImage(Image image,Point point)

当我完成它时,我排除了处理图像对象的内存泄漏.我知道这些图像没有被破坏,并且在面板停止显示之前程序执行一段时间后可以正常读取.

我遇到同样的问题,当使用PictureBox,但这一次至少我得到一个错误,而不是没有.

我检查了任务管理器中的GDI对象和USER对象,但是当应用程序工作时,它们总是大约有65个用户对象和165个GDI对象.

我确实需要到底,尽管它不像我可以在.NET系统库中插入断点,看看执行失败的位置.

提前致谢.

编辑:这是显示代码

private void DrawImage(Image image)
{
  Point leftCorner = new Point((this.Bounds.Width / 2) - (image.Width / 2),(this.Bounds.Height / 2) - (image.Height / 2));
  _graphics.DrawImage(image,leftCorner);
}

图像加载代码

private void LoadImage(string filename,ref Image image)
{
  MemoryStream memoryStream = DecryptImageBinary(Settings.Default.ImagePath + filename,_cryptPassword);

  image = Image.FromStream(memoryStream);

  memoryStream.Close();
  memoryStream.Dispose();
  memoryStream = null;
}

_image是全局的,它的引用在LoadImage中更新.它们作为参数传递,因为我想从尽可能少的地方更改全局引用,并保持其他方法自包含. _graphics也是全球性的.

我也有网站的webBrowser控件,我一次显示一个图像或一个网站.当有时间显示图像时,执行以下代码

webBrowser.Visible = false;
panel.Visible = true;
DrawImage(_image)
_image.Dispose();
_image = null;

_image正在引用预加载的图像.

希望这可以帮助.

解决方法

你的问题类似于我的想法,但不完全相同.当您加载图像时,您正在从MemoryStream加载它.您必须在图像的整个生命周期中保持流的开放状态,请参阅 MSDN Image.FromStream.

You must keep the stream open for the lifetime of the Image.

解决方案是在FromImage函数中复制图像:

private void LoadImage(string filename,ref Image image)
{
  using (MemoryStream memoryStream = DecryptImageBinary(Settings.Default.ImagePath + filename,_cryptPassword))
  {
      using (tmpImage = Image.FromStream(memoryStream))
      { 
         image = new Bitmap(tmpImage);
      }
  }

}

类似于我提到的处理问题,图像似乎工作,然后当底层流被垃圾回收时随机失败.

原文链接:https://www.f2er.com/csharp/95280.html

猜你在找的C#相关文章