PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 27, 2022

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

 July 27, 2022     c#, crop, image, winforms     No comments   

Issue

How can I crop a part of an image with a polygon? For example I have 6 coordinates and I would like to cut this part of an image.

enter image description here


Solution

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));
..


Answered By - TaW
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing