Convert BitmapImage to byte[] array in Windows Phone 8.1 Runtime

天涯浪子 提交于 2019-12-31 02:53:14

问题


There are a few samples to do this but they are for Windows Phone 8.0 or 8.1 Silverlight.

But how can you do this for Windows Phone 8.1 Runtime?


回答1:


You cannot extract the pixels from a Windows.UI.Xaml.Media.Imaging.BitmapImage.

The most general solution is to use a WriteableBitmap instead of a BitmapImage. These classes are both BitmapSources and can be used almost interchangeably. The WriteableBitmap provides access to its pixel data via its PixelBuffer property:

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

Otherwise you will need to acquire the pixels from wherever the BitmapImage got them from. Depending on how the BitmapImage was initialized you may be able to find its origin from its UriSource property. The WinRT Xaml Toolkit has an extension method FromBitmapImage to create a WriteableBitmap from an BitmapImage based on its UriSource.

An ugly option would be to render the BitmapImage into an Image, create a RenderTargetBitmap based on the Image and then get its Pixels with RenderTargetBitmap.CopyPixelsAsync()




回答2:


Tried this?

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


来源:https://stackoverflow.com/questions/34184855/convert-bitmapimage-to-byte-array-in-windows-phone-8-1-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!