Monthly Archives: March 2008

A generic error occurred in GDI+ when reading from MemoryStream

I am playing with TagLib#, an Open Source library that supports reading and updating ID3 metadata from MP3 files. I ran across the following error — “a generic error occurred in gdi+” — displaying a bitmap image I pulled from the MP3 file.

   TagLib.File file = TagLib.File.Create(@"foo.mp3");
   int pictureCount = file.Tag.Pictures.Length;
   System.Drawing.Bitmap bmp = null;
   if (pictureCount > 0)
   {
      System.IO.MemoryStream pictureBitstream = new System.IO.MemoryStream(
                                                    file.Tag.Pictures[0].Data.Data);
      bmp = new System.Drawing.Bitmap(pictureBitstream);
      pictureBitstream.Close();

      string fn = "foo.jpg";

      // create thumbnail
      using (System.Drawing.Image thumb =
                      bmp.GetThumbnailImage(10, 10,
                               new System.Drawing.Image.GetThumbnailImageAbort(
                                        delegate { return false; }),
                               IntPtr.Zero))
      {
         thumb.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
      }
   }

The “a generic error occurred in gdi+” message is not very helpful. I did some googling and came up with a few helpful posts on the matter, including several that appeared to be different problems. Looks like 4 Guys from Rolla have functional code.

My problem was in closing the stream too soon, which was not obvious to me at first, though makes some sense. The fix is to defer

      pictureBitstream.Close();

until after the Bitmap object is done with its work. I was initially under the illusion that once I’d created the stream for the image it read the whole image; of course that’s not true – it is not read in until it is read in.

I would submit this is a confusing UI design. Developers deserve better affordances. Good thing an exception was thrown; otherwise, this may have blown up later in a less obvious manner or at a less convenient time.

Advertisements