在Windows 10 UAP中将BitmapImage或IRandomAccessStream转换为字节数组

use*_*235 1 c# bitmap bitmapimage windows-phone-8.1 win-universal-app

谁能帮我。我不明白如何将BitmapImage或IRandomAccessStream转换为字节数组。我尝试:

foreach (StorageFile file in files)
{
    BitmapImage src = new BitmapImage();

    using (IRandomAccessStream stream = await file.OpenReadAsync())
    {
        await src.SetSourceAsync(stream);

        WriteableBitmap bitMap = new WriteableBitmap(src.PixelWidth, src.PixelHeight);
        await bitMap.SetSourceAsync(stream);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我有WriteableBitmap并尝试以下方法:

private byte[] ImageToByeArray(WriteableBitmap wbm)
{
    using (Stream stream = wbm.PixelBuffer.AsStream())
    using (MemoryStream memoryStream = new MemoryStream())
    {
        stream.CopyTo(memoryStream);
        return memoryStream.ToArray();
    }
}
Run Code Online (Sandbox Code Playgroud)

但这对我不起作用;(

Jon*_*Jon 5

应该这样做:

    async Task<byte[]> Convert(IRandomAccessStream s)
    {
        var dr = new DataReader(s.GetInputStreamAt(0));
        var bytes = new byte[s.Size];
        await dr.LoadAsync((uint)s.Size);
        dr.ReadBytes(bytes);
        return bytes;
    }
Run Code Online (Sandbox Code Playgroud)