ObservableCollection和image的UWP应用程序序列化
我使用ObservableCollection和image的UWP应用程序序列化,uwp,Uwp,我使用observateCollection并将BitmapImage存储在那里。试图使用Newtonsoft.Json序列化ObservableCollection,它只保存文本。希望以字节形式保留图像,但未找到如何将BitmapImage转换为Byte[] 总的来说,我有两个问题: 是否将图像的可观察收集序列化为文件 如何将位图图像转换为字节数组 这个问题与UWP平台有关,我将非常感谢您的帮助 ObservableCollection图像是否要序列化为文件 无法从位图图像中提取位图。无法将其
observateCollection
并将BitmapImage
存储在那里。试图使用Newtonsoft.Json序列化ObservableCollection
,它只保存文本。希望以字节形式保留图像,但未找到如何将BitmapImage
转换为Byte[]
总的来说,我有两个问题:
可观察收集
序列化为文件位图图像
转换为字节数组位图图像中提取位图。无法将其保存到文件中
您可以使用WriteableBitmap
而不是位图
,然后可以获取WriteableBitmap
的像素数据
public static async Task<FileUpdateStatus> SaveToPngImage(this WriteableBitmap bitmap, PickerLocationId location, string fileName)
{
var savePicker = new FileSavePicker
{
SuggestedStartLocation = location
};
savePicker.FileTypeChoices.Add("Png Image", new[] { ".png" });
savePicker.SuggestedFileName = fileName;
StorageFile sFile = await savePicker.PickSaveFileAsync();
if (sFile != null)
{
CachedFileManager.DeferUpdates(sFile);
using (var fileStream = await sFile.OpenAsync(FileAccessMode.ReadWrite))
{
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);
Stream pixelStream = bitmap.PixelBuffer.AsStream();
byte[] pixels = new byte[pixelStream.Length];
await pixelStream.ReadAsync(pixels, 0, pixels.Length);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
(uint)bitmap.PixelWidth,
(uint)bitmap.PixelHeight,
96.0,
96.0,
pixels);
await encoder.FlushAsync();
}
FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(sFile);
return status;
}
return FileUpdateStatus.Failed;
}
谢谢你的回答,我就是这么想的。在项目中,我将使用WriteableBitmap。非常感谢。
private byte[] ImageToByeArray(WriteableBitmap wbp)
{
using (Stream stream = wbp.PixelBuffer.AsStream())
using (MemoryStream memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}