我想我终于找到了你的问题所在。在你的ObservableCollection中,我个人不会将图像保存在其中。相反,我会保留一个BitmapSource以使用更少的资源,但是你可能有自己的理由。
我的处理流程如下:
- 将Image.Source(BitmapSource)转换为byte []
- 将byte []保存到存储器中
- 从存储器中加载byte []
- 将byte []转换为Image.Source(BitmapSource)
将通用类型保存到独立存储中(在我的实用程序类IsolatedStorage_Utility.cs中)
public static void Save<T>(string fileName, T item)
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(fileName, FileMode.Create, storage))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(fileStream, item);
}
}
}
将通用文件加载到隔离存储中(在我的实用类IsolatedStorage_Utility.cs中)
public static T Load<T>(string fileName)
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(fileName, FileMode.Open, storage))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
return (T)serializer.ReadObject(fileStream);
}
}
}
将BitmapSource转换为byte[](在我的实用程序类Image_Utility.cs中)
public static byte[] ImageToByteArray(BitmapSource bitmapSource)
{
using (MemoryStream stream = new MemoryStream())
{
WriteableBitmap writableBitmap = new WriteableBitmap(bitmapSource);
Extensions.SaveJpeg(writableBitmap, stream, bitmapSource.PixelWidth, bitmapSource.PixelHeight, 0, 100);
return stream.ToArray();
}
}
将byte[]转换为BitmapSource(在我的实用类Image_Utility.cs中)
public static BitmapSource ByteArrayToImage(byte[] bytes)
{
BitmapImage bitmapImage = null;
using (MemoryStream stream = new MemoryStream(bytes, 0, bytes.Length))
{
bitmapImage = new BitmapImage();
bitmapImage.SetSource(stream);
}
return bitmapImage;
}
示例
private void TestImageConversion(object sender, RoutedEventArgs e)
{
byte[] image1AsByteArray = Image_Utility.ImageToByteArray((BitmapSource)Image1.Source);
IsolatedStorage_Utility.Save<byte[]>("Image1.jpg", image1AsByteArray);
BitmapSource image1AsBitmapImage = Image_Utility.ByteArrayToImage(IsolatedStorage_Utility.Load<byte[]>("Image1.jpg"));
Image2.Source = image1AsBitmapImage;
}
请记住这是一个jpg保存。如果您想保存png,则需要使用CodePlex库或创建自己的PNG编码器。
希望这可以帮助您!