0

I have a windows form Program where the user can draw Polygon with the mouse on a PictureBox1 And then click on the crop button to crop the shape and display it in a different PictureBox2. Here Is My code:

private void CropBtn_Click(object sender, EventArgs e){

    // calculate the Height and The Width of the Polygon
    NewClipW = PolygonMaxX - PolygonMinX;
    NewClipH = PolygonMaxy - PolygonMiny;
    // THIS LINE WHERE I change the Result Image Dimensions 
    var ResultBitmap= new Bitmap(PictureBox1 .Image.Width, PictureBox1 .Image.Height);
    Bitmap orginalBitMap = (Bitmap)Bitmap.FromFile(OrgImgPath);
    var g = Graphics.FromImage(ResultBitmap);
    var brush = new TextureBrush(orginalBitMap);
    g.FillPolygon(brush, myPolygon.ToArray());
    targetBitmap = Transparent2Color(ResultBitmap, Color.White);
    PictureBox2.Image = targetBitmap;
    ResultBitmap.Save(@"test.jpg");
}

you can see in this code I have the Polygon Height and Width. My Problem is that If I set the Bitmap of the new cropped Image to the Polygon Height and Width the I got uncompleted or empty result as shown in the Picture:

enter image description here

If I set the Bitmap of the new cropped Image to the Height and Width of the original Image I got a lot of white spaces.

enter image description here

I think the reason is that the TextureBrush is copying the image inside the Polygon into the new image in the same place.Note That my Images are usually too big with a shape of (4301, 2677) what to do to fix it?

LarsTech
  • 80,625
  • 14
  • 153
  • 225
Engm
  • 19
  • 3
  • [How to draw a transparent shape over an Image](https://stackoverflow.com/a/62724726/7444103): see the `GetScaledSelectionRect()` method in the C# version of that code (at the bottom) -- Remember to [set the Vertical / Horizontal resolution](https://learn.microsoft.com/en-us/dotnet/api/system.drawing.bitmap.setresolution) of the new Bitmap to the same values read from the original. – Jimi Aug 03 '22 at 15:16
  • See also: [How to crop an elliptical region of an Image with smooth borders](https://stackoverflow.com/a/61554272/7444103) – Jimi Aug 03 '22 at 15:21

0 Answers0