A couple of questions:
- First and foremost: you are confused by the connection between the
PictureBox.Image (Property) and the Graphics that you associate with the PictureBox surface . The Graphics object that you get from Control.CreateGraphics can only draw on the surface of the control; usually not what you want; and even when you do this, you usually want to do this in the Paint event using e.Graphics ..
So, although your code seems to work, it only draws inconsistent pixels on the surface. Collapse / expand and you will see what the fickle means ...!
To change the bmp Bitmap , you need to associate it with the Grahics object as follows:
Graphics g = Graphics.FromImage(bmp);
Now you can draw in it:
g.DrawImage(sourceBitmap, targetArea, sourceArea, GraphicsUnit.Pixel);
After that, you can assign the Bitmap to the Image property of the TargetPicBox .. property.
Finally, get rid of Graphics , or better, put it in a using clause.
I assume that you were able to give rectCropArea meaningful values.
Also note that when copying the original bitmap, an error occurs: if you want to get the full image, use its Size (*), and not one of the PictureBox !!
And instead of creating the target rectangle with the same error, just use TargetPicBox.ClientRectangle !
Here is a sample code for the trim button:
// a Rectangle for testing Rectangle rectCropArea = new Rectangle(22,22,55,99); // see the note below about the aspect ratios of the two rectangles!! Rectangle targetRect = TargetPicBox.ClientRectangle; Bitmap targetBitmap = new Bitmap(targetRect.Width, targetRect.Height); using (Bitmap sourceBitmap = new Bitmap(SrcPicBox.Image, SrcPicBox.Image.Width, SrcPicBox.Image.Height) ) using (Graphics g = Graphics.FromImage(targetBitmap)) g.DrawImage(sourceBitmap, targetRect, rectCropArea, GraphicsUnit.Pixel); if (TargetPicBox.Image != null) TargetPicBox.Dispose(); TargetPicBox.Image = targetBitmap;
- Of course, you should have prepared a rectangle in the right mouse events!
- Here you would like to decide on the aspect ratio of the result; You probably don't want to distort the result! Therefore, you need to decide whether to trim the source rectangle trim or expand the target rectangle ..!
- If you are unsure of the resolution of dpi, you should use SetResolution to make sure the new image has the same!
Please note that since I assign targetBitmap TargetPicBox.Image , I must not let it go ! Instead, before I assign a new Image , I first Dispose old ..