如果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(未装配),你将不得不使用互操作,而不是。你有一个解决方案here,并且可以总结如下:加入
[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;
}
任何错误处理,这是不产品代码。
注意:如果你需要一个图标,你可以使用图标构造函数接收流:
using (MemoryStream m = new MemoryStream(resourceManagedBytes)) {
bmp = (Icon)new Icon(m);
}
你应该相应改变的返回类型。
这完全正常,您正在加载图标,而不是图像。使用Icon.FromHandle()代替。之后,在确定Icon对象不能再次使用后,必须使用DestroyIcon再次销毁该图标。 –