Search code examples
c#imagecrop

C# crop image trapezoid / polygon


I've got an image and I want to cut out a trapezoid from an image.

I've got 8 different coordinates like this (8 values to form a polygon with 4 Points)

pointA(222,222)
pointB(666,234)
pointC(678,235)
pointD(210,220)

I only found out how to crop images with bitmap.Clone like this

var x = pointA.x;
var y = pointA.y;
var height = pointD.y - pointA.y;
var width = pointB.x - pointA.x;
Bitmap image = new Bitmap(imagepath);
var rect = new Rectangle(x, y, wight, height);
var newImage = image.Clone(rect, image.PixelFormat);

This will create a straight rectangle and the important parts of the sub-parts wich I want to cut out are disappearing.

So, how to cut out a trapezoid using c# and .net framework core from a console environment?

I want to cut out a trapezoid but I just figured out the better form to describe what I want is a polygon.


Solution

  • One way to do it is to use the Graphics API. This has a FillPolygon method that takes a list of points and a brush. To use the source bitmap you would use the TextureBrush. Put this together and you would end up with something like this:

        public Bitmap FillPolygon(Bitmap sourceBitmap, PointF[] polygonPoints)
        {
            var targetBitmap = new Bitmap(256, 256);
            using var g = Graphics.FromImage(targetBitmap);
            using var brush = new TextureBrush(sourceBitmap);
            g.FillPolygon(brush, polygonPoints);
            return targetBitmap;
        }
    

    I think this should work from a windows console. There have historically been a few issues using some graphics APIs without a windows sessions, but I do not think this is a problem anymore.

    For maximum compatibility you could always triangulate and rasterize the trapezoid yourself and copy the selected pixels, but it would probably be significantly more work.