2013-02-21 66 views
0
public static async Task SaveFileAsync(string FileName, T data) 
{ 
    MemoryStream memStream = new MemoryStream(); 
    DataContractSerializer serializer = new DataContractSerializer(typeof(T)); 
    serializer.WriteObject(memStream, data); 

    StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(FileName, 
     CreationCollisionOption.ReplaceExisting); 
    using (Stream stream = await file.OpenStreamForWriteAsync()) 
    { 
     memStream.Seek(0, SeekOrigin.Begin); 
     await memStream.CopyToAsync(stream); 
     await stream.FlushAsync(); 
    } 
} 

public static async Task<T> RestoreFileAsync(string FileName) 
{ 
    T result = default(T); 
    try 
    { 
     StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(FileName); 
     using (IInputStream inStream = await file.OpenSequentialReadAsync()) 
     { 
      DataContractSerializer serializer = new DataContractSerializer(typeof(T)); 
      result = (T)serializer.ReadObject(inStream.AsStreamForRead()); 
      return result; 
     } 
    } 

    catch (FileNotFoundException) 
    { 
     return default(T); 
    } 
} 

序列化的BitmapImage我使用這些方法來序列化我的數據, 但我有一個包含一個圖像需要的類別,在WinRT中

[DataMember] 
Public Image img{get;set;} 

我試圖序列化。 我做的實際上是下面

var thumb = await item.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.PicturesView, 
         1000, Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale); 

BitmapImage bmg = new BitmapImage(); 
bmg.SetSource(thumb); 
Image img = new Image(); 
img.Source = bmg; 

我試圖序列化的BitmapImage它自身卻是同樣的問題。 我不斷收到此錯誤,並且我的BitmapImage有一個屬性。

類型 'Windows.UI.Xaml.Media.ImageSource' 不能被序列化。考慮使用DataContractAttribute屬性標記它,並使用DataMemberAttribute屬性標記要序列化的所有成員。如果類型是一個集合,請考慮使用CollectionDataContractAttribute來標記它。有關其他支持的類型,請參閱Microsoft .NET Framework文檔。

回答

0

DataContractSerializer不適用於圖像。您應該使用BitmapEncoder(如果您正在處理WriteableBitmap或簡單地序列化您的BitmapImage的源地址。如果位圖是從本地路徑或臨時URL加載的,並且想要保留整個位圖 - 則無法提取無論如何你需要從BitmapImage位圖位,所以你需要從原始的源URL下載源文件或複製你加載的本地文件,然後你可以將該副本保存爲一個鬆散的文件或序列化,比如你的創建的Base64 XML。

+0

Filip,我從圖像中看到一個縮略圖,你可以看到, 問題是我沒有一個名字來複制到我的本地文件夾並以Uri的形式檢索它。上面的代碼,我需要保存bitmapImage,或它的來源,a nd我沒有任何想法做這兩個操作。 如果你可以提供一個簡單的例子,那會很好, 謝謝。 – 2013-02-21 09:02:00

+0

沒有簡單的例子。您無法序列化BitmapImage本身,句點。如果它是使用Uri加載的 - 則可以保存Uri或使用它來加載原始圖像的字節。如果它被加載了一個流 - 你需要跟蹤該流的來源,並且當你需要序列化BitmapImage時 - 你可以序列化(已經序列化的)流。順便說一句,如果你的視頻縮略圖問題得到解決,你可以接受一個答案或添加自己的,如果你找到了另一個? – 2013-02-21 09:15:07

+0

如果您的意思是如何從視頻中獲取縮略圖,代碼如上所示,var thumb = item.GetThumbnailAsync(...),其中item是StorageFile,對不起,但我的英文不太好。 :D – 2013-02-21 09:25:01