【问题标题】:Convert ImageSource to WriteableBitmap in Metro Windows 8在 Metro Windows 8 中将 ImageSource 转换为 WriteableBitmap
【发布时间】:2012-08-03 14:40:41
【问题描述】:

我想知道如何将ImageSource 对象(在我的例子中是图像元素的源属性)转换为WriteableBitmapWriteableBitmap(BitmapSource) 构造函数在 Windows 8 Metro 中不起作用,所以我不能这样做。

我尝试将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);

我还添加了我在网上找到的这个辅助方法:

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

问题是BitmapImage 不再有StreamSource 方法。

【问题讨论】:

  • 哦 - 最好编辑它以删除 M 字... :-)

标签: c# windows-runtime windows-store-apps writeablebitmap imagesource


【解决方案1】:

WinRT XAML 平台在位图类中有一些不幸的限制。 WinRT XAML Toolkit 有一个您可以查看的 FromBitmapImage 方法。它基本上采用原始源并基于该源加载 WriteableBitmap。目前它仅限于安装应用程序的位图,但这应该很容易扩展到来自网络的文件(例如,使用WebFile 类下载图像)。您需要执行一些特定于应用程序的代码的唯一情况是,如果您使用 SetStream 加载 BitmapImage - 原始 Uri 会丢失,但在这种情况下 - 您也可以使用 WriteableBitmap 而不是 BitmapImage 和可以在 WriteableBitmaps 之间复制像素/字节。

【讨论】:

    【解决方案2】:

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

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

    Source

    【讨论】:

    • 虽然理论上可以回答这个问题,it would be preferable 在这里包含答案的基本部分,并提供链接以供参考。
    猜你喜欢
    • 2012-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-22
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多