【发布时间】:2015-05-06 05:32:30
【问题描述】:
我有一个包含BITMAP 结构的变量。该结构体定义如下。
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct BITMAP
{
public Int32 Type;
public Int32 Width;
public Int32 Height;
public Int32 WidthBytes;
public UInt16 Planes;
public UInt16 BitsPixel;
public IntPtr Bits;
}
这个结构没有错。当我尝试使用 GDI GetObject API 获取位图时,它会填充真实数据。
当我尝试将其转换为字节数组并再次返回时出现问题。
您将在下面看到我如何将结构转换为字节数组。这又一次正常工作,我看到了数组中的数据。
var bitmap = new BITMAP();
var bufferSize = Marshal.SizeOf(bitmap);
GetObject(bitmapHandle, bufferSize, out bitmap);
var bytes = new byte[bitmap.WidthBytes * bitmap.Height];
Marshal.Copy(bitmap.Bits, bytes, 0, bytes.Length);
DeleteObject(bitmapHandle);
//"bytes" now contains the byte array of pixels.
现在,一切都出了问题。当我稍后尝试将此给定数组转换回BitmapImage 时,我得到NotSupportedException。
这是我的转换代码。
var image = new BitmapImage();
using (var stream = new MemoryStream(bytes))
{
stream.Position = 0;
image.BeginInit();
image.CreateOptions = BitmapCreateOptions.None;
image.CacheOption = BitmapCacheOption.OnDemand;
image.UriSource = null;
image.StreamSource = stream;
image.EndInit(); //it throws the exception here
}
image.Freeze();
异常消息是No imaging component suitable to complete this operation was found。
我曾尝试在网上寻找解决方案,但没有成功。我似乎无法弄清楚我做错了什么。我假设它正在从BITMAP 到字节数组的转换过程中,但我不知道。
应该注意,BitmapSource 也可以。
【问题讨论】:
-
您确定要使用 BitmapImage 吗?还是 BitmapSource?
-
是的。我需要在 WPF 应用程序中显示它。
-
是的,没错。大多数 WPF 应用程序不需要 BitmapImage。例如,Image 控件(在 XAML 中使用)不需要 BitmapImage,它只需要一个 ImageSource(它是基类,BitmapSource 派生自它,BitmapImage 派生自 BitmapSource)。因此我的问题。你最后想做什么?
-
啊哈。那么 BitmapSource 也可以。
-
我认为不需要任何代码。与其帮助我们处理这个有严重缺陷的代码,不如解决真正的问题。那么,真正的问题是什么?你的实际目标是什么。