How to view images in WPF

The Image Class

The Image class is used to load and view an image in WPF. This class displays .bmp, .gif, .ico, .jpg, .png, .wdp, and .tiff files. If a file is a multiframe image, only the first frame is displayed. The frame animation is not supported by this class.

 

The Source property of Image class is the file an image displays. The Source property is a BitmapImage, which can be converted using the following code:

 

ImageViewer1.Source = new BitmapImage(new Uri("Creek.jpg", UriKind.Relative));

 

In the above code snippet, UriKind lets you set if the image is relative to the application path or has an absolute path.

 

I create a WPF application with two labels, a button, and an Image control. The XAML code looks like this:

 

<StackPanel Orientation="Horizontal" Background="LightBlue" Height="40">

    <Label Margin="10,0,0,0" Height="23" Name="Label1">

        Current File:

    </Label>

    <Label Margin="5,0,0,0" Height="25" Name="FileNameLabel" Width="300" />

    <Button Margin="5,0,0,0" Height="23" Name="BrowseButton" Width="75" Click="BrowseButton_Click">

        Browse

    </Button>               

    </StackPanel>

<StackPanel >

    <Image Name="ImageViewer1" Height="400" Width="400" />      

</StackPanel>

 


The Browse button click event handler looks like following:

 

 

private void BrowseButton_Click(object sender, RoutedEventArgs e)

{

    OpenFileDialog dlg = new OpenFileDialog();

    dlg.InitialDirectory = "c:\\";

    dlg.Filter = "Image files (*.jpg)|*.jpg|All Files (*.*)|*.*";

    dlg.RestoreDirectory = true;

 

    if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)

    {

        string selectedFileName = dlg.FileName;

        FileNameLabel.Content = selectedFileName;

        BitmapImage bitmap = new BitmapImage();

        bitmap.BeginInit();

        bitmap.UriSource = new Uri(selectedFileName);

        bitmap.EndInit();

        ImageViewer1.Source = bitmap;

    }

}

Click on the Browse button to let you browse the files and the selected file will be displayed in the Viewer.