【发布时间】:2017-12-17 11:30:56
【问题描述】:
我正在尝试从非托管资源 dll 加载图像,并且在将从 dll 检索到的 btye 数组转换为位图图像时无法克服错误。
在 Visual Studio 中查看时,test.dll 文件包含以下结构:
test.dll
位图
+411
图标
+1002[英语(美国)
当我双击 ID 411(Bimap 节点)时,我可以在位图编辑器中看到 bmp 文件 当我双击 ID 1002(图标节点)时,我可以在图标编辑器中看到不同的图标。
所以我确定它们是有效的位图和图标,但是当我在下面运行测试时,它无法将字节数组转换为图像,因为它捕获了“参数无效 Image.FromStream(...”) 错误。
有谁知道这是怎么回事。
代码如下:
public partial class Form1 : Form
{
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr
LoadLibraryEx(string lpFileName, IntPtr hFile, int dwFlags);
[DllImport("kernel32.dll")]
static extern IntPtr FindResource(IntPtr hModule, int lpName, int lpType);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr LoadResource(IntPtr hModule, IntPtr hResInfo);
[DllImport("kernel32.dll", SetLastError = true)]
static extern uint SizeofResource(IntPtr hModule, IntPtr hResInfo);
const int DATAFILE = 2;
const int BITMAP_TYPE = 2;
const int ICON_TYPE = 3;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
IntPtr loadLib = LoadLibraryEx("tsjcore.dll", IntPtr.Zero, DATAFILE);
IntPtr findRes = FindResource(loadLib, 411, 2);
IntPtr loadRes = LoadResource(loadLib, findRes);
// Gives the correct size of image as
uint size = SizeofResource(loadLib, findRes);
byte[] imageArray = new byte[size];
// Loads the imageArray with data when viewed in debug mode.
Marshal.Copy(loadRes, imageArray, 0, (int)size);
Bitmap bitmap;
try
{
using (MemoryStream memoryStream = new MemoryStream(imageArray))
{
bitmap = (Bitmap)Bitmap.FromStream(memoryStream);
}
}
catch (Exception ex)
{
// displays parameter is not valid Image.FromStream(....
MessageBox.Show(ex.ToString());
}
}
}
【问题讨论】:
标签: c# .net c#-3.0 pinvoke dllimport