C# Image Clip

Image Clipping

Clipping an image in C# is perhaps not obvious but not difficult. Clipping bitmaps in .NET is useful when programmers need only a segment of the bitmap.

Because the clipping is handled with built-in GDI+ libraries (as part of the Graphics class) the speed is decent.

How to Clip

To clip the image we basically want to redraw only the segment we want onto a new bitmap. A simple and fast way to do so is with the DrawImage function in the Graphics class (under the System.Drawing namespace of course).

Of course that is is pseudocode to explain the particular overload of the DrawImage function we need. By matching the size of the destination and source rectangles the clipped bitmap will be not distorted. This is important because DrawImage will resize the clipped bitmap to fit the destination rectangle if it does not fit.

Selecting the Bitmap Area

This part has nothing to do with clipping an image in C#. However to make the code easier to understand the demo application includes the user interface to easily select the clipping area of the image. While it is not something as advanced as Photoshop, the code gets the job done.

The trick is to keep track of the clipping rectangle as a field variable. Then by attaching a MouseMove event to the picturebox, we can update the corners of the clipping rectangle as the user drags them around. How do we know which corner the user is dragging? We use the distance formula function to figure out which corner is the closets to the mouse cursor.

The Demo Application

The demo application shows very well how to clip images in C#.NET. To avoid complicating the code, the pictureboxes will not accomodate big images, however that is only a limitation of the user interface. The underlying code works fine for images of any size.