Image Viewer in WPF

The attached project with this article is a simple Image Viewer that allows users to browse an image and display it in WPF and XAML.
  • 6919
 

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:

<Image Name="ImageViewer1" Height="400" Width="400" Source="Dock.jpg" />

In the above code snippet, UriKind let 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 following:

      <StackPanel Orientation="Vertical">
            <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" Source="Dock.jpg" />
            </StackPanel>
        </StackPanel>

The application UI looks like Figure 1.

ImageViewerImg1.jpg

Figure 1.

The Browse button click event handler looks like following:

    Private Sub BrowseButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)

        Dim dlg As OpenFileDialog = New OpenFileDialog()
        dlg.InitialDirectory = "c:\\"
        dlg.Filter = "Image files (*.jpg)|*.jpg|All Files (*.*)|*.*"
        dlg.RestoreDirectory = True
 
        If dlg.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            Dim selectedFileName As String = dlg.FileName
            FileNameLabel.Content = selectedFileName
            Dim bitmap As BitmapImage = New BitmapImage()
            bitmap.BeginInit()
            bitmap.UriSource = New Uri(selectedFileName)
            bitmap.EndInit()
            ImageViewer1.Source = bitmap
        End If
    End Sub


Click on the Browse button let you browse the files and selected file is displayed in the Viewer. See Figure 2.

ImageViewerImg2.jpg

Figure 2.

Summary

This article showed how to use the Image control of WPF to load and view the image files. I will be working with this Image Viewer for a while and will build a full-fledged image viewer.

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.