Recipe 10.2. Displaying Image Files


You want to display pictures, possibly selected by the user, in your Visual Basic 2005 application.


Sample code folder: Chapter 10\ShowJPG

The OpenFileDialog class provides a standard way to let the user select any file, such as a picture to be displayed, and the PictureBox control gives you a great way to display pictures.


It's easy to use an OpenFileDialog control on a form to let the user select a file from anywhere in the system. Create a new Windows Forms application, add a PictureBox control to Form1 named SelectedPicture, and add a Button control named ActLocate. Set the PictureBox's SizeMode property to StretchImage. Add the following code to the button's Click event handler:

 Private Sub ActLocate_Load(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles ActLocate.Click    ' ----- Let the user choose a picture.    Dim locateFile As New OpenFileDialog    locateFile.Filter = "JPG files (*.jpg)|*.jpg"    locateFile.Multiselect = False    If (locateFile.ShowDialog( ) = _          Windows.Forms.DialogResult.OK) Then       ' ----- Show the selected picture.       SelectedPicture.Load(locateFile.FileName)    End If End Sub 

Figure 10-1 shows the OpenFileDialog during a typical session in which the user is about to select a JPEG picture file.

If a JPEG file is selected, it is loaded into the form's PictureBox for display. It takes only one command to load the picture:


Figure 10-2 shows the picture as displayed in the PictureBox on the form.

Figure 10-1. Using the OpenFileDialog control to select a picture file

Figure 10-2. Displaying pictures on a form with a PictureBox control

Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: