如果 Dll 是 .NET 程序集,您可以调用Assembly.GetManifestResourceStream
,如下所示:
public static Bitmap getBitmapFromAssemblyPath(string assemblyPath, string resourceId) {
Assembly assemb = Assembly.LoadFrom(assemblyPath);
Stream stream = assemb.GetManifestResourceStream(resourceId);
Bitmap bmp = new Bitmap(stream);
return bmp;
}
如果它是本机 dll(不是程序集),则必须改用 Interop。您在这里有一个解决方案,可以总结如下:
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags);
[DllImport("kernel32.dll")]
static extern IntPtr FindResource(IntPtr hModule, int lpID, string 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);
[DllImport("kernel32.dll", SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool FreeLibrary(IntPtr hModule);
static const int LOAD_LIBRARY_AS_DATAFILE = 0x00000002;
public static Bitmap getImageFromNativeDll(string dllPath, string resourceName, int resourceId) {
Bitmap bmp = null;
IntPtr dllHandle = LoadLibraryEx(dllPath, IntPtr.Zero, LOAD_LIBRARY_AS_DATAFILE);
IntPtr resourceHandle = FindResource(dllHandle, resourceId, resourceName);
uint resourceSize = SizeofResource(dllHandle, resourceHandle);
IntPtr resourceUnmanagedBytesPtr = LoadResource(dllHandle, resourceHandle);
byte[] resourceManagedBytes = new byte[resourceSize];
Marshal.Copy(resourceUnmanagedBytesPtr, resourceManagedBytes, 0, (int)resourceSize);
using (MemoryStream m = new MemoryStream(resourceManagedBytes)) {
bmp = (Bitmap)Bitmap.FromStream(m);
}
FreeLibrary(dllHandle);
return bmp;
}
没有添加错误处理,这不是生产就绪代码。
注意:如果您需要 Icon,您可以使用接收流的 Icon 构造函数:
using (MemoryStream m = new MemoryStream(resourceManagedBytes)) {
bmp = (Icon)new Icon(m);
}
您应该相应地更改返回类型。