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

前端 未结 2 352
借酒劲吻你
借酒劲吻你 2021-01-20 13:16

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?

相关标签:
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;
    }
    
    0 讨论(0)
  • 2021-01-20 14:02

    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()

    0 讨论(0)
提交回复
热议问题