GDI+ Image Handling in C# (
Page 1 of 3 )
Learn how to easily handle images of different formats using GDI+ in C#.
It was a dream come true when I learned in July 2000 that the .NET framework included image loading, saving, and manipulation. Before that time, you had to either buy a third-party library or write your own code to load and save images. I did both at various times, and each had their fair share of pitfalls.
This article shows you how to use images in your application by calling on the GDI+ classes that provide the needed functionality. It's so easy now that it's hard for me to convince new programmers that in the past, images were difficult to manage.
The Graphics Class
As with all GDI+ methods, we'll draw to a surface (similar to a canvas). The surface can be anything including the physical screen, a printer, or an in-memory bitmap. The Graphics class abstractly represents surfaces so that programmers can forget about the exact surface device. All drawing is done in the same way.
Click here for a more complete discussion on the Graphics class.
We'll get started learning how to use the Graphics class by creating a simple Windows C# application named LearnImagesClass. Once the application project has been created, we'll go to the form properties, click on the events button (the lightning bolt), and add an OnPaint event handler.
The default method that is created contains a sender object (which I have never used in this context) and a PaintEventArgs object. The wizard-created method is shown below:
private void OnPaint(object sender, PaintEventArgs e)
{
}
One of the members of the PaintEventArgs object is a Graphics object named Graphics. All methods and properties of this Graphics object can be accessed as e.Graphics.SomeGDIMethodCall(). The following example uses the Graphics object to draw a line:
e.Graphics.DrawLine(new Pen(Color.Black), 0, 0, 250, 250);