2014-03-30 22 views
0

你好,我想問你一個問題。以XML格式編寫課程的一部分

我創建了一個Person類,我寫了人名,姓氏,ID和圖像。

現在我想把這個類保存爲.xml和image。我找到了將類保存爲.xml的解決方案,但不會將任何圖像保存到.xml文件中。

private void SaveasXML() 
{ 
    XmlSerializer serializer = new XmlSerializer(typeof(BindingList<Person>)); 
    FileStream fileStream = File.Create(Application.StartupPath + "\\Data\\Person.xml"); 
    serializer.Serialize(fileStream, New_Xml_Person); 
} 

我想用圖像保存所有信息到.xml文件中。要將圖像保存爲.xml文件,應將其轉換爲base64string。我知道但我無法使用它。

有什麼建議嗎?謝謝。

+0

你需要保存在XML文件中的實際圖像還是你只想路徑保存? –

+0

你如何在課堂上存儲圖像?你能分享你的人員代碼嗎? – thepirat000

+0

圖像可以保存爲已轉換的base64strings。我Person類的最後拿到集部分: \t \t [XmlElementAttribute( 「圖片」) \t \t公衆的byte [] PictureByteArray \t \t { \t \t \t得到 \t \t \t { \t \t \t \t如果(picture!= null) \t \t \t \t { \t \t \t \t \t TypeConverter BitmapConverter = TypeDescriptor.GetConverter(picture.GetType()); (byte [])\t BitmapConverter.ConvertTo(picture,typeof(byte [])); \t \t \t \t \t \t \t \t \t} \t \t \t \t其他 \t \t \t \t \t返回NULL; \t \t \t} \t \t \t \t \t \t設置 \t \t \t { \t \t \t \t如果(值!= null) \t \t \t \t \t picture = new Bitmap(new MemoryStream(value)); \t \t \t \t別的 \t \t \t \t \t圖象= NULL; \t \t \t} \t \t} – user3478916

回答

0

您可以向您的Person類添加一個byte [] ImageBuffer屬性,該類包含二進制圖像數據。然後,您還可以在Image屬性上設置XmlIgnore屬性以禁止其(反)序列化,並在ImageBuffer屬性上將XmlElement(「Image」)設置爲(de)將其序列化爲Image。

更新答案:

[XmlIgnoreAttribute()] 
    public Bitmap Picture { get { return picture; } set { picture = value; } } 

    [XmlElementAttribute("Picture")] 
    public byte[] PictureByteArray { 
     get { 
      if (picture != null) { 
       using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) 
           { 
         picture.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); 
            return ms.ToArray(); 
        } 
      } else return null; 
     } 
     set { 
      if (value != null) 
      { 
       using (System.IO.MemoryStream ms = new System.IO.MemoryStream(value)) 
            { 
                 picture = new Bitmap(Image.FromStream(ms)); 
            } 
      } 
      else picture = null; 
     } 
    } 
+0

我改變文本: [XmlIgnoreAttribute()] \t \t公共位圖圖片 \t \t { \t \t \t得到{圖片; } \t \t \t set {picture = value; } \t \t} [XmlElementAttribute( 「圖片」) \t \t公衆的byte [] PictureByteArray \t \t { \t \t \t得到 \t \t \t { \t \t \t \t如果(圖片!= NULL) \t \t \t \t { \t \t \t \t \t TypeConverter BitmapConverter = TypeDescriptor.GetConverter(picture.GetType()); (byte [])\t BitmapConverter.ConvertTo(picture,typeof(byte [])); \t \t \t \t \t \t \t \t \t} \t \t \t \t其他 \t \t \t \t \t返回NULL; \t \t \t} \t \t \t \t \t \t設置 \t \t \t { \t \t \t \t如果(值!= NULL) \t \t \t \t \t圖象=新位圖(新的MemoryStream(值)); \t \t \t \t別的 \t \t \t \t \t圖象= NULL; \t \t \t} \t \t} 但它沒有工作。 – user3478916

+0

我現在沒有電腦來測試它,但更新的答案應該可以工作... – StefanoGermani

+0

它的工作。非常感謝你的兄弟。你現在真的幫了我。 :) – user3478916