When drawing an image: System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI

后端 未结 2 2010
感情败类
感情败类 2020-12-06 06:20

I\'ve got a global Graphics object created from a Panel. At regular intervals an image is picked up from the disk and drawn into the panel using Graphics.DrawImage(). It wor

2条回答
  •  长情又很酷
    2020-12-06 06:32

    Your problem is similar to what I thought, but not quite. When you are loading the image, you are loading it from a MemoryStream. You have to keep the stream open for the lifetime of the image, see MSDN Image.FromStream.

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

    The solution is to make a copy of your image in the FromImage function:

    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);
          }
      }
    
    }
    

    Similar to the dispose problem I mentioned, the image will seem to work and then randomly fail when the underlying stream is garbage collected.

提交回复
热议问题