Serialize a Bitmap in C#/.NET to XML(将 C#/.NET 中的位图序列化为 XML)
问题描述
我想要XML-Serialize一个复杂类型(类),它有一个System.Drawing.Bitmap类型的属性等等.
I want to XML-Serialize a complex type (class), that has a property of type System.Drawing.Bitmap among others.
/// <summary>
/// Gets or sets the large icon, a 32x32 pixel image representing this face.
/// </summary>
/// <value>The large icon.</value>
public Bitmap LargeIcon { get; set; }
我现在发现用默认的 XML 序列化器序列化 Bitmap 是行不通的,因为它没有公共的无参数构造函数,这是默认的 xml 序列化器所必需的.
I now have found out that serializing the Bitmap with the default XML serializer does not work, because it does not have a public parameterless constructor, which is mandatory with the default xml serializer.
我知道以下几点:
- 存在一种变通方法,发布在此处:http://www.dotnetspider.com/resources/4759-XML-Serialization-C-Part-II-Images.aspx.但是,由于这包括添加另一个属性,这在我看来有点麻烦.
- 在 sourceforge 上还有一个深度 XML 序列化项目.
- There exists a workaround, posted here: http://www.dotnetspider.com/resources/4759-XML-Serialization-C-Part-II-Images.aspx . However since this includes adding another property this seems to me a bit of a hack.
- There is also a deep XML serializing project on sourceforge.
我宁愿不喜欢引用另一个项目,也不喜欢大量调整我的类以只允许这些位图的 xml 序列化.
I rather would not like referencing another project nor extensively tweak my class to just allow xml serialization of those bitmaps.
就没有办法保持这么简单吗?
非常感谢,马塞尔
推荐答案
我会这样做:
[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);
}
}
}
}
这篇关于将 C#/.NET 中的位图序列化为 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 C#/.NET 中的位图序列化为 XML


- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 使用 rss + c# 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01