C# Programming > Drawing GDI+

Four-Point Image Distortion

c# bitmap

Update: Thank you to a kind reader for submitting a bug fix, the code has been updated.

C# GDI+

The .Net Framework GDI+ comes with some useful functions to transform images. However they only handle image transformations based on points that are perpendicular/parallel to each other. If you want to transform an image with non-perpendicular sides then you are on your own.

Four-Point Distortion

This C# application is going to distort an image based on the location of four distinct corner points. An example of this is in Photoshop's Free Transform. Our application will not be anywhere near as fast as Photoshop, but given that there is very little support and information for this type of image transformation, our application is pretty good...

The distortion is going to be done using math to take a point from the source bitmap and find its corresponding coordinate in the final distorted image. And like many other image processing applications, we have to decide how to interpolate.

Image Interpolation

Interpolation in image processing is using pixels around a specific coordinate to "average out" the color that should be placed. Interpolation slows down the speed of image processing but it generates bitmaps that are way smoother.

Usually for speed there is no need to interpolate when the user is specifying the location of the corner points, then once all points are set then interpolation is applied to generate a higher quality image. If you use Photoshop you are familiar with this format.

The Math

The general concept of the math to distort the image is to calculate the points of intersection of the corner points. Then as the program transverses through the image, each pixel is checked for intersection with the image's sides and some simple multiplying and dividing is done with all the points of intersection. Look over the csharp souce code to see what I mean.

Using the Code

The code is put into a nice easy-to-use C# class which you can call like this:

Bitmap newBmp = QuadDistort.Distort(sourceBmp, topLeft, topRight, bottomLeft, bottomRight);

Additionally there is an overload that allows you to specify the size of the interpolation grid.

Known Issues

Once you run the sample C# application you will quickly find out that the code is extremely slow. It only runs decently on small images. But again, given that this image distortion algorithm has basically no support in .NET I'd say it's a good place to start.

Back to C# Article List