How to read an image file in C#

By FoxLearn 11/12/2024 9:30:53 AM   3.52K
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.

c# read image file

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