Ioannis Panagopoulos blog

Tutorials on HTML5, Javascript, WinRT and .NET

Image Resources in WinForms and WPF

by Ioannis Panagopoulos

Suppose you have a picture control in your form (WinForms) / window (WPF) and want to display the following picture in it (logo.png):

In a Window Forms application you create a PictureBox control in your form, and in the code file you want to do something like the following:

this.pictureBoxTestImage.Image = //An Image object for logo.png should be here

There are three ways of setting this reference (eg. creating the needed Image object).

1) You can drag and drop the logo.png file in the Resources.resx file. Visual Studio will automatically create a reference to it and you can safely write:

this.pictureBoxTestImage.Image = Properties.Resources.logo;

2) You can put the file in a folder. Usually you create a new folder in Solution Explorer withih the project and add there the desired file (in our case logo.png). Then, you make sure that in the properties of the file Buid Action is set to None and Copy To Output Directory is set to Copy Always. This will copy the files when you compile the application to the Debug\ or Release\ folder and you can safely use the following to display the image (in the following example logo.png is located in the Resources\ folder):

Image bitmap = Bitmap.FromFile(".\\Resources\\logo.png");
this.pictureBoxTestImage.Image = bitmap;

3) You can also put the file in the folder within solution explorer and set in the properties Buid Action to Embedded Resource. This will embed logo.png in the .exe file of the application. You can use this file with the following code (this is a good method if you dont want your images to be easily changed by the app user):

System.IO.Stream stream;
System.Reflection.Assembly assembly;
Image bitmap;

this.pictureBoxTestImage.Image = bitmap;

In WPF things are a bit diferent. First of all the Embedded Resource Build Action is substituted by the Resource Build Action. Nevertheless, they do the same job but they cannot be used interchangeably. Using the Resources.resx file is not easy any more. To be more specific now you have the following:

<Image Margin="278,118,230,239" Name="TestImage" Stretch="Fill"/>

The easiest way to put logo.png in there is to add it to the project preferably in a folder (eg Images\), set the Build Action to Resource and then call the following in the code-behind file:

TestImage.Source=new BitmapImage(new Uri("/Images/logo.png",UriKind.Relative));

Note that UriKind and the Uri object are kinda tricky with the way the path should be specified. For reference see this and this.

blog comments powered by Disqus
hire me