Windows Phone 8.1 Runtime - Image to byte []和Vice Versa

时间:2015-12-03 18:23:30

标签: windows-runtime windows-phone-8.1 bytearray bitmapimage writeablebitmap

对于我的应用程序,我正在尝试将WriteableBitmap转换为byte[]以存储在数据库中,然后从byte[]转换为BitmapImage以显示回用户。

到目前为止,我目前的方法没有产生任何结果:

public byte[] ConvertBitmapToByteArray(WriteableBitmap bitmap)
{
    using (Stream stream = bitmap.PixelBuffer.AsStream())
    using (MemoryStream memoryStream = new MemoryStream())
    {
        stream.CopyTo(memoryStream);
        return memoryStream.ToArray();
    }
}

要从字节数组转换为BitmapImage,我使用:

using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
{

    using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
    {
        writer.WriteBytes((byte[])buffer);
        writer.StoreAsync().GetResults();
    }


    var image = new BitmapImage();
    image.SetSource(ms);
    imageByteTest.Source = image;
}            

我找到了很好的Silverlight应用程序文档,但对于Windows Store Universal Runtime应用程序却没什么用处。这些方法在哪里出错?

2 个答案:

答案 0 :(得分:0)

您可能需要查看包含WriteableBitmap的一些扩展的WriteableBitmapEx库,以及一些核心功能,例如将WriteableBitmap转换为字节数组,反之亦然。

答案 1 :(得分:0)

我为ByteArrayToBitmapImage写了一个转换器:

 public object Convert(object value, Type targetType, object parameter, string language)
    {
        var byteArray = value as byte[];
        var bitmapImage = new BitmapImage();
        Window.Current.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                using (var stream = new MemoryStream(byteArray))
                {
                    bitmapImage.SetSourceAsync(stream.AsRandomAccessStream());
                }
            });

        return bitmapImage;

    }

和byte [] - > WriteableBitmap的

  public static WriteableBitmap PrepareWritableBitmap(Size size, byte[] pixels)
    {
        uint height = (uint)Math.Floor(size.Height);
        uint width = (uint)Math.Floor(size.Width);

        WriteableBitmap bmp = new WriteableBitmap((int)width, (int)height);
        Stream pixStream = bmp.PixelBuffer.AsStream();
        pixStream.Write(pixels, 0, (int)(width * height * 4));
        //4 is a channel number for RGBA, for RGB is 3 channels
        return bmp;
    }