Thomas Sampson


Leave a comment

Loading image resources onto a form in WPF

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];
}


Reflective Glass

I am aware that there is most likely to be a much simpler implementation of this as part of WPF (Windows Presentation Foundation) but this article shows you how to make a reflective glass effect (similar to that used throughout itunes) using GDI library only (in c#).

http://www.codeproject.com/KB/GDI-plus/Image-Glass-Reflection.aspx