How to create a simple image browser in WPF using c sharp

This post explains following steps:

  • Browse your PC for image files.
  • Choose an image.
  • The image is displayed inside an image control of your WPF application.
  • The physical path of the image is shown in a text box.

First, create a new WPF application and take one text box, one button and one image control.

The physical path of the image will be shown inside the text box. name it imagePathTextBox. The image will be displayed inside the image control. name it myImage. Name the button, browserBtn and generate a new event.

Inside the event handler in the cs page, write the following code:

 

var fd = new Microsoft.Win32.OpenFileDialog();
fd.Filter = “All image formats (*.jpg; *.jpeg; *.bmp; *.png; *.gif)|*.jpg;*.jpeg;*.bmp;*.png;*.gif”;
var ret = fd.ShowDialog();

if (ret.GetValueOrDefault())
{
imagePathTextBox.Text = fd.FileName;

try
{
BitmapImage bmp = new BitmapImage(new Uri(fd.FileName, UriKind.Absolute));
myImage.Source = bmp;
}
catch (Exception)
{
MessageBox.Show(“Invalid image file.”, “Browse”, MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
}

Now, browse and open an image, see the results.

Download the source code.