首页 > 代码库 > Image(支持 XML 序列化),注意C#中原生的Image类是无法进行Xml序列化的

Image(支持 XML 序列化),注意C#中原生的Image类是无法进行Xml序列化的

 1     /// <summary> 2     /// Image(支持 XML 序列化) 3     /// </summary> 4     [XmlRoot("XmlImage")] 5     public class XmlImage : IXmlSerializable 6     { 7         public System.Drawing.Image Image { get; set; } 8  9         #region 构造函数10 11         public XmlImage()12         { }13 14         protected XmlImage(SerializationInfo info, StreamingContext context)15         { }16         #endregion 构造函数17 18         #region IXmlSerializable Members19         public XmlSchema GetSchema() => null;20 21         /// <summary>22         ///     从对象的 XML 表示形式生成该对象(反序列化)23         /// </summary>24         /// <param name="xr"></param>25         public void ReadXml(XmlReader xr)26         {27             if (xr.IsEmptyElement)28                 return;29             xr.ReadToFollowing(nameof(XmlImage));30             Image = FromBase64String(xr.ReadElementContentAsString());31             xr.ReadEndElement();32         }33 34         /// <summary>35         ///     将对象转换为其 XML 表示形式(序列化)36         /// </summary>37         /// <param name="xw"></param>38         public void WriteXml(XmlWriter xw)39         {40             xw.WriteStartElement(nameof(XmlImage));41             xw.WriteValue(ToBase64String(Image, ImageFormat.Png));42             xw.WriteEndElement();43         }44         #endregion IXmlSerializable Members45 46         private static string ToBase64String(System.Drawing.Image img, ImageFormat format)47         {48             if (img != null)49             {50                 using (var ms = new MemoryStream())51                 {52                     img.Save(ms, format);53                     byte[] buffer = ms.ToArray();54                     return Convert.ToBase64String(buffer);55                 }56             }57             return string.Empty;58         }59 60         private static System.Drawing.Image FromBase64String(string base64Str)61         {62             System.Drawing.Image img = null;63             using (var ms = new MemoryStream())64             {65                 try66                 {67                     var buffer = Convert.FromBase64String(base64Str);68                     ms.Write(buffer, 0, buffer.Length);69                     img = System.Drawing.Image.FromStream(ms);70                 }71                 catch72                 {73                     // ignored74                 }75             }76             return img;77         }78     }

 

Image(支持 XML 序列化),注意C#中原生的Image类是无法进行Xml序列化的