Home > Backend Development > C++ > How to Load Images from Embedded Resources in C#?

How to Load Images from Embedded Resources in C#?

Mary-Kate Olsen
Release: 2025-01-20 21:08:11
Original
317 people have browsed it

How to Load Images from Embedded Resources in C#?

Loading embedded resource images 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:

var bmp = new Bitmap(WindowsFormsApplication1.Properties.Resources.myimage);
Copy after login

Use System.Resources.ResourceManager: You can manually create a ResourceManager to retrieve resources:

using System.Resources;

// 为当前程序集创建一个资源管理器
var rm = new ResourceManager(Assembly.GetExecutingAssembly());

// 从指定的资源名称加载图像
var bmp = (Bitmap)rm.GetObject("myimage");
Copy after login

In a WPF application:

Use PackUri: In WPF you can use PackUri to load images from resources:

var img = new Image();
img.Source = new BitmapImage(new Uri("pack://application:,,,/Resources/myimage.jpg"));
Copy after login

Use System.Windows.Media: Another option for WPF is to leverage System.Windows.Media:

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();
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template