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 = new PictureBox();
imageControl.Width = 400;
imageControl.Height = 400;
Controls.Add(imageControl);
VB.NET Code:
Dim imageControl As New PictureBox()
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:
private void DisplayImage()
{
PictureBox imageControl = new PictureBox();
imageControl.Width = 400;
imageControl.Height = 400;
Bitmap image = new Bitmap("C:\\Images\\Creek.jpg");
imageControl.Dock = DockStyle.Fill;
imageControl.Image = (Image)image;
Controls.Add(imageControl);
}
VB.NET Code:
Private Sub DisplayImage()
Dim imageControl As New PictureBox()
imageControl.Width = 400
imageControl.Height = 400
Dim Image As New Bitmap("C:\\Images\\Creek.jpg")
imageControl.Dock = DockStyle.Fill
imageControl.Image = Image
Controls.Add(imageControl)
End Sub
The output looks like Figure 1 where an image is displayed.
SizeMode
SizeMode 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