public override void Serialize(
BsonWriter bsonWriter,
Type nominalType,
object value,
IBsonSerializationOptions options)
{
if (nominalType != typeof(Image) && nominalType != typeof(Bitmap))
{
var message = string.Format("Nominal type must be Image or Bitmap, not {0}.", nominalType.FullName);
throw new ArgumentException(message, "nominalType");
}
if (value == null)
{
bsonWriter.WriteNull();
}
else
{
var actualType = value.GetType();
if (actualType != typeof(Bitmap))
{
var message = string.Format("Actual type must be Bitmap, not {0}.", actualType.FullName);
throw new ArgumentException(message, "actualType");
}
var bitmap = (Bitmap)value;
var stream = new MemoryStream();
bitmap.Save(stream, ImageFormat.Bmp);
var bytes = stream.ToArray();
if (nominalType == typeof(Image))
{
bsonWriter.WriteStartDocument();
bsonWriter.WriteString("_t", "Bitmap");
bsonWriter.WriteBytes("bitmap", bytes);
bsonWriter.WriteEndDocument();
}
else
{
bsonWriter.WriteBytes(bytes);
}
}
}
}