ObservableCollection和image的UWP应用程序序列化

ObservableCollection和image的UWP应用程序序列化,uwp,Uwp,我使用observateCollection并将BitmapImage存储在那里。试图使用Newtonsoft.Json序列化ObservableCollection,它只保存文本。希望以字节形式保留图像,但未找到如何将BitmapImage转换为Byte[] 总的来说,我有两个问题: 是否将图像的可观察收集序列化为文件 如何将位图图像转换为字节数组 这个问题与UWP平台有关,我将非常感谢您的帮助 ObservableCollection图像是否要序列化为文件 无法从位图图像中提取位图。无法将其

我使用
observateCollection
并将
BitmapImage
存储在那里。试图使用Newtonsoft.Json序列化
ObservableCollection
,它只保存文本。希望以字节形式保留图像,但未找到如何将
BitmapImage
转换为
Byte[]

总的来说,我有两个问题:

  • 是否将图像的
    可观察收集
    序列化为文件
  • 如何将
    位图图像
    转换为字节数组
  • 这个问题与UWP平台有关,我将非常感谢您的帮助

    ObservableCollection图像是否要序列化为文件

    无法从
    位图图像中提取位图。无法将其保存到文件中

    您可以使用
    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();  
       }  
    }