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 Members 19 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 Members 45 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 try 66 { 67 var buffer = Convert.FromBase64String(base64Str); 68 ms.Write(buffer, 0, buffer.Length); 69 img = System.Drawing.Image.FromStream(ms); 70 } 71 catch 72 { 73 // ignored 74 } 75 } 76 return img; 77 } 78 }