Reputation:
I have the following problem:
I have an image saved as: Image X;
and a list of Point.
point is defined as following:
public struct Point
{
public int X;
public int Y;
}
on the list (which isn't sorted) there are 2 Points. the Points represent cords on the image. these cords define a rectangle shape. for example if cords are: (0,0) and (1,1) then the rectangle edges are: (0,0) - (0,1) - (1,1) - (1,0).
I am suppose to write a method that returns a cropped image where the rectangle lays. in the above example the cropped image will be everything within the boundary of (0,0) - (0,1) - (1,1) - (1,0).
any ideas for simple way to implement it?
note that i can't know where the rectangle lays in the image X. rectangles can have same area or even the exact same shape but in different places on the image.
assume it can be anywhere yet rectangle can not be outside of the image in any way (whole nor partly)
Upvotes: 0
Views: 631
Reputation: 15151
First of all, you need to get the min corner and the max corner, an easy way is:
//Having p1 and p2
Point min = new Point(Math.Min(p1.X, p2.X), Math.Min(p1.Y, p2.Y));
Point max = new Point(Math.Max(p1.X, p2.X), Math.Max(p1.Y, p2.Y));
Once you have max and min you can construct a rectangle for source:
Rectangle srcRect = new Rectangle(min.X, min.Y, max.X - min.X, max.Y - min.Y);
Then you create a Bitmap with the rect size:
Bitmap cropped= new Bitmap(srcRect.Width, srcRect.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
Create a Graphics object from the image:
Graphics g = Graphics.FromImage(bmp);
And draw the cropped area:
//Having source image SrcImg
g.DrawImage(SrcImage, new Rectangle(Point.Empty, srcRect.Size), srcRect, GraphicsUnit.Pixel);
Now you have your cropped image at "cropped"
Don't forget to dispose graphics!!
Upvotes: 1