Hi all, I expect using C# to serialize a Bitmap would be straight forward, but it turns out that I am wrong. I tried with the code below but I failed to get the image data. class Program { static void Main(string[] args) { Bitmap corolla = new Bitmap(@"C:\corolla.jpg", true); // some image file. MemoryStream ms = new MemoryStream(); XmlTextWriter xw = new XmlTextWriter(ms, Encoding.UTF8); xw.Formatting = Formatting.Indented; XmlSerializer ser = new XmlSerializer(typeof(Bitmap)); ser.Serialize(xw, corolla); Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray())); } } I understand that I can use the Bitmap.Save() and save it to a MemoryStream. However, what I am going to do is to stick with the XmlSerializer. I did try to inherit from the XmlSerializer class, but I failed to implement the CreateWriter and CreateReader method which simply return some abstract class with adequate documentation. Any suggestion are appreciated. Thanks.
Hello Tony, I think the reason is just that the Bitmap class (or rather the Image base class) isn't prepared for XML serialization. You can serialize it just fine with the System.Runtime.Serialization functionality, for which it has support: Bitmap corolla = new Bitmap(@"C:\Users\Oliver\Documents\test.png", true); MemoryStream ms = new MemoryStream( ); SoapFormatter formatter = new SoapFormatter( ); formatter.Serialize(ms, corolla); Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray())); If you want to stay with XML serialization, I suggest you create a wrapper class that implements IXmlSerializable, use the Image.Save() method to save the bitmap contents to a stream and convert that stream to base64 or similar, to include in the XML serialization by way of your interface implementation. Oliver Sturm --
Don't see what you're looking for? Try a search.
|