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