0

I'm trying to crop an image, but the image doesn't get cropped properly

The code I'm using to get part of the picture I want is

Bitmap bmap = new Bitmap(pictureBox1.Image, pictureBox1.Width, pictureBox1.Height);
Bitmap cropImg = new Bitmap(cropArea.Width, cropArea.Height);
Graphics g = Graphics.FromImage(cropImg);
g.DrawImage(bmap, 0, 0, cropArea, GraphicsUnit.Pixel);
return cropImg;

the result I get is weird

Crop Reuslt :

crop result

The cropped picture gets blurred and zoomed in(?). What could be the cause the problem and what could I do to get rid of it?

JJIqbal
  • 630
  • 1
  • 8
  • 23
bapster
  • 151
  • 8
  • It seems the code is taken from [this question](https://stackoverflow.com/q/734930/1997232). What is `cropArea`? It seems you are not calculating rectangle vertical offset and height correctly. – Sinatr May 20 '19 at 09:49
  • cropArea is the rectangle that represents the selected area – bapster May 20 '19 at 09:57
  • Depending on the SizeMode you will have to do a of calculating to scale the mousecoordinates to suit the pb sizemode. [Example](https://stackoverflow.com/questions/30436313/convert-picturebox-selection-rectangle-according-to-sizemode/30437608?r=SearchResults&s=1|57.7281#30437608) – TaW May 20 '19 at 11:05
  • @TaW I've been playing with the sample you provided, but still can't get the crop function to work properly :( https://imgur.com/a/OCWWlYi crop method code: https://imgur.com/a/yVMgaW4 – bapster May 22 '19 at 05:38
  • Whart sizemode is the pbox in? – TaW May 22 '19 at 06:37
  • @TaW it's Squeeze – bapster May 22 '19 at 06:42
  • I've changed the mode to 'Stretch' and it seems to work as expected. Thank you a lot :) – bapster May 22 '19 at 06:47
  • Good to hear. It wasn't really in 'Squeeze' mode, right ;-) – TaW May 22 '19 at 07:04
  • How can I calculate it so it works with zoom mode? I need to let the user zoom in/out and still crop the correct part of picture @TaW – bapster May 29 '19 at 13:51
  • Explain exactly how the user zooms! – TaW May 29 '19 at 13:58
  • @TaW I have an UI control that lets the user zoom based on percentage like this https://i.imgur.com/8ebTHkx.jpg – bapster May 29 '19 at 14:04
  • I didn't mean the UI; I meant how do you realize it in your picturebox? Do you change the pbox.Size? Is it embedded in a Panel? – TaW May 29 '19 at 14:07

1 Answers1

0

You can try crop by cloning the original image, but only taking a rectangle of the original.

private static Image cropImage(Image img, Rectangle cropArea)
{
   Bitmap bmpImage = new Bitmap(img);
   Bitmap bmpCrop = bmpImage.Clone(cropArea,
   bmpImage.PixelFormat);
   return (Image)(bmpCrop);
}