PictureBox In C#

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

  1. PictureBox imageControl = newPictureBox();  
  2. imageControl.Width = 400;  
  3. imageControl.Height = 400;  
  4. Controls.Add(imageControl);  

VB.NET Code

  1. Dim imageControl AsNewPictureBox()  
  2. imageControl.Width = 400  
  3. 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

  1. privatevoid DisplayImage()   
  2. {  
  3.     PictureBox imageControl = newPictureBox();  
  4.     imageControl.Width = 400;  
  5.     imageControl.Height = 400;  
  6.     Bitmap image = newBitmap("C:\\Images\\Creek.jpg");  
  7.     imageControl.Dock = DockStyle.Fill;  
  8.     imageControl.Image = (Image) image;  
  9.     Controls.Add(imageControl);  
  10. }  

VB.NET Code

  1. PrivateSub DisplayImage()  
  2. Dim imageControl AsNewPictureBox()  
  3. imageControl.Width = 400  
  4. imageControl.Height = 400  
  5. Dim Image AsNewBitmap("C:\\Images\\Creek.jpg")  
  6. imageControl.Dock = DockStyle.Fill  
  7. imageControl.Image = Image  
  8. Controls.Add(imageControl)  
  9. EndSub  

The output looks like Figure 1 where an image is displayed.

PictureBox

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

  1. imageControl.SizeMode = PictureBoxSizeMode.CenterImage;  

VB.NET Code

  1. 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



Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.