How can I crop original image in a pictureBox that shows image in Stretch mode?
I changed pictureBox1_MouseUp code to :
void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
xUp = e.X;
yUp = e.Y;
Rectangle rec = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown));
using (Pen pen = new Pen(Color.YellowGreen, 3))
{
pictureBox1.CreateGraphics().DrawRectangle(pen, rec);
}
xDown = xDown * pictureBox1.Image.Width / pictureBox1.Width;
yDown = yDown * pictureBox1.Image.Height / pictureBox1.Height;
xUp = xUp * pictureBox1.Image.Width / pictureBox1.Width;
yUp = yUp * pictureBox1.Image.Height / pictureBox1.Height;
rectCropArea = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown));
}
And it's worked. Thanks to 'Hans Passant' for his answer.
Soheila Hg
Graduate of computer science with experience working across the full-stack of software development. Capable of working with a variety of technology and software solutions, and managing databases. I’m looking for an opportunity that provides more challenges and focuses on Data Science, where I can develop and expand my skills.
Updated on November 25, 2022Comments
-
Soheila Hg over 1 year
How can I crop an image in a pictureBox that shows in Stretch mode?
I draw a rectangle in pictureBox :
void pictureBox1_MouseUp(object sender, MouseEventArgs e) { //pictureBox1.Image.Clone(); xUp = e.X; yUp = e.Y; Rectangle rec = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown)); using (Pen pen = new Pen(Color.YellowGreen, 3)) { pictureBox1.CreateGraphics().DrawRectangle(pen, rec); } rectCropArea = rec; } void pictureBox1_MouseDown(object sender, MouseEventArgs e) { pictureBox1.Invalidate(); xDown = e.X; yDown = e.Y; }
and crop the selected part with :
private void btnCrop_Click(object sender, EventArgs e) { try { pictureBox3.Refresh(); //Prepare a new Bitmap on which the cropped image will be drawn Bitmap sourceBitmap = new Bitmap(pictureBox1.Image, pictureBox1.Width, pictureBox1.Height); Graphics g = pictureBox3.CreateGraphics(); //Draw the image on the Graphics object with the new dimesions g.DrawImage(sourceBitmap, new Rectangle(0, 0, pictureBox3.Width, pictureBox3.Height), rectCropArea, GraphicsUnit.Pixel); sourceBitmap.Dispose(); } catch (Exception ex) { } }
but the quality of the cropped image is very low because it cropped the stretch Image not the original image. How can I crop the original image with size of rectangle that User drawing in pictureBox?
-
user1703401 over 10 yearsYou must map the mouse position to image coordinates to determine what needs to be cropped. When you use Stretch then it is simply x = e.X * image.Width / pictureBox.Width.
-
Soheila Hg over 10 yearsThank you Hans Passant, It's worked.
-