在Metro Windows 8中将ImageSource转换为WriteableBitmap

GGC*_*GCO 5 c# imagesource writeablebitmap windows-runtime windows-store-apps

我想知道如何将ImageSource对象(在我的例子中是图像元素的source属性)转换为WriteableBitmap.该WriteableBitmap(BitmapSource)构造函数无法在Windows 8地铁工作,所以我不能这样做.

我试图将ImageSource对象加载到流然后使用WriteableBitmap.SetSource(stream),但我无法弄清楚如何在流中加载图像.

InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
BitmapEncoder enc = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ras);

byte[] pixelArray = new byte[(uint)photoBox.Height * (uint)photoBox.Width * 4];

enc.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight,
                 (uint)photoBox.Width, (uint)photoBox.Height, 96, 96, pixelArray);
Run Code Online (Sandbox Code Playgroud)

我还添加了我在网上找到的帮助方法:

public Byte[] BufferFromImage(BitmapImage imageSource)
{
    Stream stream = imageSource.StreamSource;
    Byte[] buffer = null;
    if (stream != null && stream.Length > 0)
    {
        using (BinaryReader br = new BinaryReader(stream))
        {
            buffer = br.ReadBytes((Int32)stream.Length);
        }
    }

    return buffer;
}
Run Code Online (Sandbox Code Playgroud)

问题是BitmapImage不再有这种StreamSource方法.

GGC*_*GCO -1

我在MSDN论坛上得到了答案。

无法从 ImageSource 中提取图像数据。您将需要跟踪信息的原始来源,并从原始来源在 WriteableBitmap 中重新创建图像。如果您知道需要这样做,那么最好一开始就使用 WriteableBitmap 作为 ImageSource。

来源