PictureBox control is used to display images in Windows Forms. In this article, I will discuss how to use a PictureBox control to display images in Windows Forms applications.
Creating a PictureBox
PictureBox class represents a PictureBox control. The following code snippet creates a PictureBox, sets its width and height and adds control to the Form by calling Controls.Add() method.
C# Code
- PictureBox imageControl = newPictureBox();
- imageControl.Width = 400;
- imageControl.Height = 400;
- Controls.Add(imageControl);
VB.NET Code
- Dim imageControl AsNewPictureBox()
- imageControl.Width = 400
- imageControl.Height = 400
Display an Image
Image property is used to set an image to be displayed in a PictureBox control. The following code snippet creates a Bitmap from an image and sets the Image property of PictureBox control. Code also sets the Dock property of PictureBox.
C# Code
- privatevoid DisplayImage()
- {
- PictureBox imageControl = newPictureBox();
- imageControl.Width = 400;
- imageControl.Height = 400;
- Bitmap image = newBitmap("C:\\Images\\Creek.jpg");
- imageControl.Dock = DockStyle.Fill;
- imageControl.Image = (Image) image;
- Controls.Add(imageControl);
- }
VB.NET Code
- PrivateSub DisplayImage()
- Dim imageControl AsNewPictureBox()
- imageControl.Width = 400
- imageControl.Height = 400
- Dim Image AsNewBitmap("C:\\Images\\Creek.jpg")
- imageControl.Dock = DockStyle.Fill
- imageControl.Image = Image
- Controls.Add(imageControl)
- EndSub
The output looks like Figure 1 where an image is displayed.
SizeModeSizeMode property is used to position an image within a PictureBox. It can be Normal, StretchImage, AutoSize, CenterImage, and Zoom. The following code snippet sets SizeMode property of a PictureBox control.
C# Code
- imageControl.SizeMode = PictureBoxSizeMode.CenterImage;
VB.NET Code
- imageControl.SizeMode = PictureBoxSizeMode.CenterImage
Summary
In this article, we discussed discuss how to use a PictureBox control to display images in Windows Forms applications.
Further Readings