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

时间:2016-01-03 21:39:52

标签: c# bitmap windows-phone-8.1 win-universal-app bitmapimage

谁能帮助我。我不明白我如何将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);
    }
}

然后我有WriteableBitmap并试试这个:

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

但它不适合我;(

2 个答案:

答案 0 :(得分:4)

这应该这样做:

    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;
    }

答案 1 :(得分:-1)

我在WPF应用程序中使用此解决方案将数据保存为byte[]。它也适用于你的情况。

public static byte[] ImageToString(System.Windows.Media.Imaging.BitmapImage img) {
    System.IO.MemoryStream stream = new System.IO.MemoryStream();
    System.Windows.Media.Imaging.BmpBitmapEncoder encoder = new System.Windows.Media.Imaging.BmpBitmapEncoder();
    encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create((System.Windows.Media.Imaging.BitmapSource)img));
    encoder.Save(stream);
    stream.Flush();

    return stream.ToArray();
}
相关问题