Minggu, 10 November 2013

How to set PictureBox Image using OpenFileDialog or Bitmap Class: WindowsForms

A person’s basic properties are name, age, date of birth, contact no. and also have a picture of that person. To insert the picture we have to preview that picture at the same time we are loading the picture. That’s why we need this picture box control on the windows forms.

Picture Box control is used to display pictures that may be jpeg, jpg, png or any bitmap file. The picture can be set during run time by the user, or can be fixed by the programmer during design time. It have many properties to be used by the programmer, to make the picture adjustable.

Picture box have some common properties that are mostly used by, which are:

  • SizeMode: used to control the clipping and positioning of the image in the display area.
  • ImageLocation: specify the image to be displayed.
  • ClientSize: used to change the size of the display area at run time.
  • BorderStyle: to distinguish the control from the rest of the form, even it have no image.

Drag-n-drop a picture box which will hold the image and button to be used to browse the image. The form will look like the image below:

How to set PictureBox Image using OpenFileDialog or Bitmap Class: WindowsForms

Generate the click event of button and write the following C# code:
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
pictureBox1.ImageLocation = ofd.FileName;
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;

When you run this project and click on the button, it will show an openFileDialog box. You have to select an image file and click on OK button. At the last the picture has been set on the picture box as shown in the below image.

How to set PictureBox Image using OpenFileDialog or Bitmap Class: WindowsForms

It is not required to set the picture as above, we can set an object also of the Image class in the System.Drawing namespace. For that, just create an object of Bitmap class and set that object to the image property of picture box, as described in the below code:
Bitmap bt = new Bitmap(“image path”);
pictureBox1.Image = bt;
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;

The most thing to be noticed in the second code, is we have to know the exact path of the image file. Run the code and it will give the same output as the first code provide.

See Also: OpenFileDialog in windows forms

Tidak ada komentar:

Posting Komentar