How to load an image in C#

By FoxLearn 12/26/2024 8:46:06 AM   13
In C#, you can load an image using the System.Drawing namespace, which provides the Image class.

To load an image off a drive you can use the static Image class like this:

using System;
using System.Drawing;  // Required for Image class

class Program
{
    static void Main()
    {
        // Specify the image file path
        string imagePath = @"C:\dell\image.jpg";
        
        // Load the image from the file
        Image image = Image.FromFile(imagePath);

        // Don't forget to dispose of the image when done
        image.Dispose();
    }
}

You must call Dispose() on the Image object after you're done with it to release the resources properly.

For .NET Core or .NET 5+, you may need to install the System.Drawing.Common package. You can do this by running the following in the terminal or NuGet package manager:

dotnet add package System.Drawing.Common