我想知道如何将ImageSource
对象(在我的情况下是图像元素的source属性)转换为WriteableBitmap
。 WriteableBitmap(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
方法。
答案 0 :(得分:2)
WinRT XAML平台在位图类中有一些不幸的限制。 WinRT XAML Toolkit有一个FromBitmapImage方法,您可以查看。它基本上采用原始源并基于该源加载WriteableBitmap。目前,它仅限于安装应用程序的位图,但这应该很容易从Web扩展到文件(例如,使用WebFile类来下载图像)。你需要做一些特定于应用程序的代码的唯一情况是你使用SetStream加载BitmapImage - 原来的Uri会丢失,但在这种情况下 - 你也可以使用WriteableBitmap而不是BitmapImage和可以在WriteableBitmaps之间复制像素/字节。
答案 1 :(得分:-1)
我在MSDN论坛上得到了答案。
无法从ImageSource中提取图像数据。您需要跟踪信息的原始来源,并从原始源重新创建WriteableBitmap中的图像。如果您知道自己需要这样做,那么最好只使用WriteableBitmap作为ImageSource开始。