How to crop a polygonal area from an image in a WinForm pictureBox? [closed]

You can make the List of Points into a Polygon, then into a GraphicsPath and then into a Region and after Graphics.Clip(Region) you can Graphics.DrawImage and are done..:

using System.Drawing.Drawing2D;

GraphicsPath gp = new GraphicsPath();   // a Graphicspath
gp.AddPolygon(points.ToArray());        // with one Polygon

Bitmap bmp1 = new Bitmap(555,555);  // ..some new Bitmap
                                    // and some old one..:
using (Bitmap bmp0 = (Bitmap)Bitmap.FromFile("D:\\test_xxx.png"))
using (Graphics G = Graphics.FromImage(bmp1))
{
    G.Clip = new Region(gp);   // restrict drawing region
    G.DrawImage(bmp0, 0, 0);   // draw clipped
    pictureBox1.Image = bmp1;  // show maybe in a PictureBox
}
gp.Dispose();  

Note that you are free to choose the DrawImage location anywhere, including in the negative area to the left and top of the origin..

Also note that for ‘real’ cropping some (at least 4) of your points should hit the target Bitmap‘s borders! – Or you can use the GraphicsPath to get its bounding box:

RectangleF rect = gp.GetBounds();
Bitmap bmp1 = new Bitmap((int)Math.Round(rect.Width, 0), 
                         (int)Math.Round(rect.Height,0));
..

Leave a Comment