问题
I'm trying to load a image from a unmanaged resource dll and have not been able to get past a error when converting the btye array retrieved from the dll to a bitmap image.
The test.dll file contains the following structure when viewed in visual studio:
test.dll
Bitmap
+411
Icon
+1002[English (United States]
and when I double click the ID 411 (Bimap node) I can see the bmp file in the bitmap editor and when I double click the ID 1002 (Icon node) I can see the differnt icons in the icon editor.
So im certain that they are valid bitmap and icons, but when I run the test for below it cannot convert byte array to image as it catches the exception with "parameter is not valid Image.FromStream(..." error.
Does anyone know what it wrong.
The code is below:
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());
}
}
}
回答1:
You are getting a pointer to the BITMAPINFOHEADER, the file header is missing. So Image.FromStream() cannot work. Pinvoke LoadBitmap() instead and use Image.FromHbitmap().
来源:https://stackoverflow.com/questions/9261800/load-bitmap-file-from-unmanaged-dll-in-managed-code