public static Bitmap Load(ResourceLoader loader, string resourceName) { using (HGlobal buffer = HGlobal.WithStringUni(resourceName)) { return(new Bitmap(NativeMethods.LoadBitmap(loader.ModuleHandle, buffer.Handle))); } }
/// <summary> /// Loads an image (of any format, including PNG or JPEG) that is embedded in a DLL. /// </summary> /// <param name="loader"> /// A <see cref="ResourceLoader"/> instance used to load the resource. /// </param> /// <param name="resourceTypeName"> /// The name of the resource type (for example, <c>IMAGE</c>). /// </param> /// <param name="resourceName"> /// The name (as used in the RC file) of the resource to load. /// </param> /// <returns> /// A <see cref="Bitmap"/> instance that must be properly disposed to avoid leaking memory. /// </returns> public static Bitmap LoadImageFromResource(ResourceLoader loader, string resourceTypeName, string resourceName) { IntPtr hResInfo; using (HGlobal namePtr = HGlobal.WithStringUni(resourceName)) { hResInfo = NativeMethods.FindResourceW(loader.ModuleHandle, resourceTypeName, namePtr.Handle); } IntPtr hResData = NativeMethods.LoadResource(loader.ModuleHandle, hResInfo); IntPtr data = NativeMethods.LockResource(hResData); int size = NativeMethods.SizeofResource(loader.ModuleHandle, hResData); if (RuntimeInformation.FrameworkDescription.Contains(".NET Native")) { throw new PlatformNotSupportedException(); } else { byte[] buffer = new byte[size]; Marshal.Copy(data, buffer, 0, size); IntPtr hMem = Marshal.AllocHGlobal(size); Marshal.Copy(buffer, 0, hMem, size); NativeMethods.IStream stream = null; try { int hr = NativeMethods.CreateStreamOnHGlobal(hMem, true, out stream); if (hr != 0) { Marshal.ThrowExceptionForHR(hr); } NativeMethods.IWICImagingFactory factory = (NativeMethods.IWICImagingFactory) new NativeMethods.WICImagingFactory(); NativeMethods.IWICBitmapDecoder decoder = factory.CreateDecoderFromStream(stream, options: NativeMethods.WICDecodeOptions.WICDecodeMetadataCacheOnDemand); decoder.GetFrame(0, out NativeMethods.IWICBitmapFrameDecode frame); return(LoadImageFromBitmapSource((NativeMethods.IWICBitmapSource)frame)); } finally { if (stream != null) { Marshal.ReleaseComObject(stream); } } } }