In lesson 3, you have learned how to add a picture box on the form in VB2013 IDE. In this lesson, you will learn how to load an image into the picture box at design time and at runtime. Besides that, you will also learn how to use a common dialog control to browse for image files in your drives; then select and load a particular image in the picture box.
First, insert a picture box on the form and change its border property to FixedSingle and its background to white. You might also want to change the size mode of the image to stretchable so that the image can fit in the picture box. Now right-click on the picture box to bring out its properties window. In the properties window, scroll to the Image property, as shown in Figure 7.1
Next, click on the gray button on its right to bring out the "Select Source" dialog box, as shown in Figure 7.2
Now select local source and click on the Import button to view the available image files in your local drives, as shown in Figure 7.3
Finally, select the image you like and then click the open button, the image will be displayed in the picture box, as shown in Figure 7.4.
In Visual Basic 2013, an image can also be loaded at runtime, using the code as follows:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load PictureBox1.Image = Image.FromFile("C:\My Pictures\USA\Chicago 2012.jpg") End Sub
* You need to search for an image in your local drive and determine its path. Running the program will display the same image in the picture box as in Figure 7.4.
We have designed the picture viewer interface in lesson 3. Now we shall write code so that the user can browse for the image files in his or her local drives then select a particular image to display in the picture box.
First, we need to add the OpenFileDialog control on the form. This control will be invisible during runtime but it facilitates the process of launching a dialog box and let the user browse his or her local drives; then select and open a file. In order for the OpenFileDialog to display all types of image files, we need to specify the types of image files under the Filter property. Before that, rename OpenFileDialog as OFGSelectImage. Next, right-click on the OpenFileDialog control to access its properties window. Beside the Filter property, specify the image files using the format:
JPEG Files| *.JPG|GIF Files|*.GIF|Windows Bitmaps|*.BMP
as shown in Figure 7.5. These are the common image file formats. Besides that, you also need to delete the default Filename.