Thomas Sampson

Loading image resources onto a form in WPF

Leave a comment

After starting out with WPF earlier this week I was surprised to find something as simple as loading an image from the applications resources, and mapping this onto an Image control, would be such a pain! Ok, its not a lot of code but it still took quite a bit of investigating. I have written the following simple function to make this procedure less tasking. This function takes two arguments, the target Image control and the name of the resource you are attempting to load (“somefile.jpg”) for example.

Usage

  • Make sure your image file is included in the project and set to embedd as a resource
  • If you are not using a jpeg, swap the JpegBitmapDecoder to one of its siblings
  • Replace “app_name” with the name of your Visual Studio project name
  • asm could be made global if required
private void GetImageResource(System.Windows.Controls.Image target, string image_name)
{
  Assembly asm = Assembly.GetExecutingAssembly();
  Stream stream = asm.GetManifestResourceStream("app_name."+image_name);
  JpegBitmapDecoder j = new JpegBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
  target.Source=j.Frames[0];
}
Advertisements

Author: tomtech999

I have recently graduated with a 1st class degree in MComp Games Software Development at Sheffield Hallam University, focusing primarily on application development in C++, with experience in graphics programming, scripting languages, DVCS/VCS and web technology. In my spare time I enjoy Drumming, Reading and Snowboarding!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s