views:

648

answers:

1

I've got a valuetype object that I'm trying to serialize (via a BinaryFormatter) but within this object there are 3 Bitmaps which, when serializing the object throw a "general gdi+ exception" (no seriously, that's the exception).

It's imperative that these bitmaps get serialized into the file (as opposed to just storing their relative locaiton and transmitting the images along with the rest of the serialized object).

The object looks much like:


[Serializable]
public struct MyObject
{
  public String whatever;
  // ...
  public Bitmap img1;
  public Bitmap img2;
}

and I serialize it like so:


BinaryFormatter bFormatter = new BinaryFormatter();
fs = new FileStream(m_ContractFolder + filename + ".xtn", FileMode.OpenOrCreate);

bFormatter.Serialize(fs, contract);

I've googled around and most of what I've found is all xmlserialization (not ideal in this situation). I'm not sure what else to do.

A: 

I've encountered something similar in the past when cloning and thumbnailing images. Unfortunately it's been a few years and I don't remember the details but it had to do with file handles and GDI holding onto them as the source for that Image object.

I resolved the issue by loading images from a MemoryStream rather than whatever the actual source stream was. If your images are in files, load the contents of the file into a MemoryStream first. Then load the image from the MemoryStream.

JD Conley