Csharp/C#教程:将C#/ .NET中的位图序列化为XML分享


将C#/ .NET中的位图序列化为XML

我想XML-Serialize一个复杂类型(类),它具有System.Drawing.Bitmap类型属性

///  /// Gets or sets the large icon, a 32x32 pixel image representing this face. ///  /// The large icon. public Bitmap LargeIcon { get; set; } 

我现在已经发现使用默认的XML序列化程序序列化Bitmap不起作用,因为它没有公共无参数构造函数,这对于默认的xml序列化程序是必需的。

我知道以下内容:

我宁愿不想引用另一个项目,也不想广泛调整我的类,只允许这些位图的xml序列化。

有没有办法保持这么简单?

非常感谢,马塞尔

我会做的事情如下:

 [XmlIgnore] public Bitmap LargeIcon { get; set; } [Browsable(false),EditorBrowsable(EditorBrowsableState.Never)] [XmlElement("LargeIcon")] public byte[] LargeIconSerialized { get { // serialize if (LargeIcon == null) return null; using (MemoryStream ms = new MemoryStream()) { LargeIcon.Save(ms, ImageFormat.Bmp); return ms.ToArray(); } } set { // deserialize if (value == null) { LargeIcon = null; } else { using (MemoryStream ms = new MemoryStream(value)) { LargeIcon = new Bitmap(ms); } } } } 

您还可以实现ISerializable并使用SerializationInfo手动处理您的位图内容。

编辑: João是对的:处理XML序列化的正确方法是实现IXmlSerializable ,而不是ISerializable

 public class MyImage : IXmlSerializable { public string Name { get; set; } public Bitmap Image { get; set; } public System.Xml.Schema.XmlSchema GetSchema() { throw new NotImplementedException(); } public void ReadXml(System.Xml.XmlReader reader) { throw new NotImplementedException(); } public void WriteXml(System.Xml.XmlWriter writer) { writer.WriteStartElement("Name"); writer.WriteString(this.Name); writer.WriteEndElement(); using(MemoryStream ms = new MemoryStream()) { this.Image.Save(ms, ImageFormat.Bmp ); byte[] bitmapData = ms.ToArray(); writer.WriteStartElement("Image"); writer.WriteBase64(bitmapData, 0, bitmapData.Length); writer.WriteEndElement(); } } } 

BitMap类尚未设计为易于XML序列化。 所以,不,没有简单的方法来纠正设计决策。

实现IXmlSerializable ,然后自己处理所有序列化详细信息。

既然你说它是一个大型的,你只有位图的问题考虑做这样的事情:

上述就是C#学习教程:将C#/ .NET中的位图序列化为XML分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 public class BitmapContainer : IXmlSerializable { public BitmapContainer() { } public Bitmap Data { get; set; } public XmlSchema GetSchema() { throw new NotImplementedException(); } public void ReadXml(XmlReader reader) { throw new NotImplementedException(); } public void WriteXml(XmlWriter writer) { throw new NotImplementedException(); } } public class TypeWithBitmap { public BitmapContainer MyImage { get; set; } public string Name { get; set; } } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1002925.html

(0)
上一篇 2021年12月27日
下一篇 2021年12月27日

精彩推荐