Load Bitmap file from unmanaged DLL in managed code

允我心安 提交于 2019-12-11 10:22:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!