How to read an image file in C#
By Tan Lee Published on Jul 11, 2017 4.04K
To read an image file in a C# Windows Forms application, you typically use the System.Drawing namespace, which provides classes for working with images.
Open Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "ReadImageFile" and then click OK
In the Designer view, drag and drop the Table, PictureBox, Button controls onto your form designer, then design your form as below.
The most commonly used class is Image
, and you can load an image into a PictureBox
control.
To allow users to select an image file and display it in a PictureBox
when they click a button, you can modify your code like this:
private void btnOpen_Click(object sender, EventArgs e) { try { //Open file dialog, allows you to select an image file using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "JPG|*.jpg|PNG|*.png|Bitmap|*.bmp", ValidateNames = true, Multiselect = false }) { // Show the dialog and check if the user selected a file if (ofd.ShowDialog() == DialogResult.OK) pictureBox.Image = Image.FromFile(ofd.FileName);// Load the selected image into the PictureBox } } catch (Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
Use OpenFileDialog
to allow users to choose an image file when the button is clicked.
VIDEO TUTORIAL
- How to Open and Show a PDF file in C#
- How to Get all Forms and Open Form with Form Name in C#
- How to zoom an image in C#
- How to Print a Picture Box in C#
- How to update UI from another thread in C#
- How to Search DataGridView by using TextBox in C#
- How to read and write to text file in C#
- How to save files using SaveFileDialog in C#
Categories
Popular Posts
Gentella Admin Template
Nov 14, 2024
11 Things You Didn't Know About Cloudflare
Dec 19, 2024
Elegant Bootstrap 5 HTML5 Admin Dashboard Template
Nov 17, 2024