Home >Backend Development >C++ >How to Load Images from Embedded Resources in C#?
Images stored in the project resource area often need to be dynamically loaded into bitmap objects for display or operation. Here's how to do this in C#:
In a Windows Forms application:
Use embedded images: If you add the image to your project using Visual Studio's Properties/Resources UI, it will be embedded as a resource. You can then access it via the generated code:
<code class="language-csharp">var bmp = new Bitmap(WindowsFormsApplication1.Properties.Resources.myimage);</code>
Use System.Resources.ResourceManager: You can manually create a ResourceManager to retrieve resources:
<code class="language-csharp">using System.Resources; // 为当前程序集创建一个资源管理器 var rm = new ResourceManager(Assembly.GetExecutingAssembly()); // 从指定的资源名称加载图像 var bmp = (Bitmap)rm.GetObject("myimage");</code>
In a WPF application:
Use PackUri: In WPF you can use PackUri to load images from resources:
<code class="language-csharp">var img = new Image(); img.Source = new BitmapImage(new Uri("pack://application:,,,/Resources/myimage.jpg"));</code>
Use System.Windows.Media: Another option for WPF is to leverage System.Windows.Media:
<code class="language-csharp">using System.Windows.Media; using System.Windows.Media.Imaging; // 获取资源流 Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Resources.myimage.jpg"); // 创建位图图像 var bmp = new BitmapImage(); bmp.BeginInit(); bmp.StreamSource = stream; bmp.EndInit();</code>
The above is the detailed content of How to Load Images from Embedded Resources in C#?. For more information, please follow other related articles on the PHP Chinese website!