首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将C#/.NET中位图序列化为XML

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

Stack Overflow用户
提问于 2009-12-15 20:23:15
回答 3查看 22.8K关注 0票数 21

我想序列化XML序列化一个复杂类型(类),它有一个System.Drawing.Bitmap类型的属性。

    /// <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序列化程序所必需的。

我知道以下几点:

上还有一个深度序列化项目

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

有没有办法让它变得简单?

非常感谢,马塞尔

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2009-12-15 20:39:01

我会这样做:

[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);
            }
        }
    }
}
票数 49
EN

Stack Overflow用户

发布于 2009-12-15 20:29:04

BitMap类并没有被设计成可以很容易地序列化。所以,不,没有简单的方法来纠正设计决策。

票数 2
EN

Stack Overflow用户

发布于 2009-12-15 20:39:13

实现IXmlSerializable,然后自己处理所有的序列化细节。

既然你说它是一个大字体,而你只对位图有一个问题,那么考虑这样做:

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; }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1907077

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档