Search code examples
c#imagebitmapcroppicturebox

How can I crop original image in a pictureBox that shows image in Stretch mode?


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?


Solution

  • 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.