在Windows Phone 8.1运行时中将BitmapImage转换为byte[]数组



有一些示例可以做到这一点,但它们适用于Windows Phone 8.0或8.1 Silverlight。

但是,如何为Windows Phone 8.1运行时做到这一点呢?

您无法从Windows.UI.Xaml.Media.Image.BitmapImage.中提取像素

最常见的解决方案是使用WriteableBitmap而不是BitmapImage。这两个类都是BitmapSources,几乎可以互换使用。WriteableBitmap通过其PixelBuffer属性提供对其像素数据的访问:

byte[] pixelArray = myWriteableBitmap.PixelBuffer.ToArray(); // convert to Array
Stream pixelStream = wb.PixelBuffer.AsStream();  // convert to stream

否则,您将需要从BitmapImage获取像素的任何位置获取像素。根据BitmapImage的初始化方式,您可以从其UriSource属性中找到其来源。WinRT-Xaml工具包有一个扩展方法FromBitmapImage,用于根据其UriSource从BitmapImage创建可写位图。

一个丑陋的选项是将BitmapImage渲染为图像,基于图像创建RenderTargetBitmap,然后使用RenderTarget位图获取其像素。CopyPixelsAsync()

尝试过这个吗?

private byte[] ConvertToBytes(BitmapImage bitmapImage)
{
    byte[] data = null;
    using (MemoryStream stream = new MemoryStream())
    {
        WriteableBitmap wBitmap = new WriteableBitmap(bitmapImage);
        wBitmap.SaveJpeg(stream, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);
        stream.Seek(0, SeekOrigin.Begin);
        data = stream.GetBuffer();
    }
    return data;
}

最新更新