Cropping Image

Requires: Visual Studio 2017

Technologies: .NET Freamework, Windows Forms, Windows, C# Language.

 

The sample shows how to crop the image and display croped image to the target PictureBox control by mouse selection or specified co-ordinates from the specific PictureBox Control.

  • How to use the mouse in a Picturebox to select a area (rectangle).
  • How the crop image through the rectangle or to the specified coordinates.

 

 

Step 1: Create a windwos application project from visual studio.

Step2: Design a From like this,

Image Cropping C#

You have to following Controls

Control Text Desing Name
Label Original Picture lblOriginalPicture
Label Cropped Picture lblCroppedPicture
PictureBox   picOriginalPicture
PictureBox   picCroppedPicture
Buttons Open btnOpen
Buttons Crop btnCrop
Buttons Save btnSave
TextBox   txtDrawX1
TextBox   txtDrawY1
TextBox   txtDrawX2
TextBox   txtDrawY2
TextBox   txtCX1
TextBox   txtCY1
TextBox   txtCX2
TextBox   txtCY2
Label X1 lblDrawX1
Label Y1 lblDrawY1
Label X2 lblDrawX2
Label Y2 lblDrawY2
Label X1 lblCX1
Label Y1 lblCY1
Label X2 lblCX2
Label Y2 lblCY2
CheckBox Use Coordinates chkCoordinates

 

Step 2: Write a code on "Open" Button Click for display image in PictureBox (picOriginalPicture)


private void btnOpenImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog openImage = new OpenFileDialog();
            openImage.Filter = "Image file(*.jpg)|*.jpg";
            openImage.RestoreDirectory = true;
            if(openImage.ShowDialog()==DialogResult.OK)
            {
                picOriginalPicture.Image =Image.FromFile(openImage.FileName);
            }
        }

 

 

Step 3: Change the both PictureBox property SizeMode to Zoom.

Change PictureBoxSize Mode to Zoom

Step4: On the source PictureBox we change the mouse cursor to "Cross".

Change Cursor Property

Step5: To Draw a rectangle on PictureBox we call the events:- MouseUp event , MouseDown event, MouseMove event, Paint event code.

First of all declare some varables on top:


Boolean mouseClicked;
        Point startPoint = new Point();
        Point endPoint = new Point();
        Rectangle rectCropArea;
        Bitmap targetBitmap;

 

Write Code For Mouse Up event:


private void picOriginalPicture_MouseUp(object sender, MouseEventArgs e)
        {
            mouseClicked = false;

            if (endPoint.X != -1)
            {
                Point currentPoint = new Point(e.X, e.Y);
                // Display coordinates
                txtDrawX2.Text = e.X.ToString();
                txtDrawY2.Text = e.Y.ToString();

            }
            endPoint.X = -1;
            endPoint.Y = -1;
            startPoint.X = -1;
            startPoint.Y = -1;
        }

Write Code For Mouse Down event:


private void picOriginalPicture_MouseDown(object sender, MouseEventArgs e)
        {
            mouseClicked = true;

            startPoint.X = e.X;
            startPoint.Y = e.Y;
            // Display coordinates
            txtDrawX1.Text = startPoint.X.ToString();
            txtDrawY1.Text = startPoint.Y.ToString();

            endPoint.X = -1;
            endPoint.Y = -1;

            rectCropArea = new Rectangle(new Point(e.X, e.Y), new Size());
        }

Write Code For Mouse move event:


private void picOriginalPicture_MouseMove(object sender, MouseEventArgs e)
        {
            Point ptCurrent = new Point(e.X, e.Y);

            if (mouseClicked)
            {
                if (endPoint.X != -1)
                {
                    // Display Coordinates
                    txtDrawX1.Text = startPoint.X.ToString();
                    txtDrawY1.Text = startPoint.Y.ToString();
                    txtDrawX2.Text = e.X.ToString();
                    txtDrawY2.Text = e.Y.ToString();
                }

                endPoint = ptCurrent;

                if (e.X > startPoint.X && e.Y > startPoint.Y)
                {
                    rectCropArea.Width = e.X - startPoint.X;
                    rectCropArea.Height = e.Y - startPoint.Y;
                }
                else if (e.X < startPoint.X && e.Y > startPoint.Y)
                {
                    rectCropArea.Width = startPoint.X - e.X;
                    rectCropArea.Height = e.Y - startPoint.Y;
                    rectCropArea.X = e.X;
                    rectCropArea.Y = startPoint.Y;
                }
                else if (e.X > startPoint.X && e.Y < startPoint.Y)
                {
                    rectCropArea.Width = e.X - startPoint.X;
                    rectCropArea.Height = startPoint.Y - e.Y;
                    rectCropArea.X = startPoint.X;
                    rectCropArea.Y = e.Y;
                }
                else
                {
                    rectCropArea.Width = startPoint.X - e.X;
                    rectCropArea.Height = startPoint.Y - e.Y;
                    rectCropArea.X = e.X;
                    rectCropArea.Y = e.Y;
                }
                picOriginalPicture.Refresh();
            }
        }

 

 

Write Code To display the dashes:


private void picOriginalPicture_Paint(object sender, PaintEventArgs e)
        {
            Pen drawLine = new Pen(Color.Red);
            drawLine.DashStyle = DashStyle.Dash;
            e.Graphics.DrawRectangle(drawLine, rectCropArea);
        }

After you select the region on the picture you want to crop, We create a Rectangle which is used in the target picture box for drawing a new Cropped Image (Zoomed). This drawing is done with the Graphics object and overload of the Graphics.DrawImage() method.

The image in the source image box can be cropped with X1, Y1, X2, Y2 in the text box, by specifying coordinates. We change the variable RectCropArea in both cropping methods.

Write Code For "Crop" button click event:


   private void btnCrop_Click(object sender, EventArgs e)
        {
            picCroppedPicture.Refresh();
            targetBitmap = new Bitmap(picCroppedPicture.ClientSize.Width, picCroppedPicture.ClientSize.Height);
            Bitmap sourceBitmap = new Bitmap(picOriginalPicture.Image, picOriginalPicture.Width, picOriginalPicture.Height);

            Graphics g = Graphics.FromImage(targetBitmap);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            g.CompositingQuality = CompositingQuality.HighQuality;
            
            if (!chkCoordinates.Checked)
            {
                g.DrawImage(sourceBitmap, new Rectangle(0, 0, picCroppedPicture.ClientSize.Width, picCroppedPicture.ClientSize.Height), rectCropArea, GraphicsUnit.Pixel);
                if (picCroppedPicture.Image != null)
                    picCroppedPicture.Image.Dispose();
                picCroppedPicture.Image = targetBitmap;
                //sourceBitmap.Dispose();
            }
            else
            {

                int x1, x2, y1, y2;
                Int32.TryParse(txtCX1.Text, out x1);
                Int32.TryParse(txtCX2.Text, out x2);
                Int32.TryParse(txtCY1.Text, out y1);
                Int32.TryParse(txtCY2.Text, out y2);

                if ((x1 < x2 && y1 < y2))
                {
                    rectCropArea = new Rectangle(x1, y1, x2 - x1, y2 - y1);
                }
                else if (x2 < x1 && y2 > y1)
                {
                    rectCropArea = new Rectangle(x2, y1, x1 - x2, y2 - y1);
                }
                else if (x2 > x1 && y2 < y1)
                {
                    rectCropArea = new Rectangle(x1, y2, x2 - x1, y1 - y2);
                }
                else
                {
                    rectCropArea = new Rectangle(x2, y2, x1 - x2, y1 - y2);
                }

                picOriginalPicture.Refresh(); // This repositions the dashed box to new location as per coordinates entered.

                g.DrawImage(sourceBitmap, new Rectangle(0, 0, picCroppedPicture.ClientSize.Width, picCroppedPicture.ClientSize.Height), rectCropArea, GraphicsUnit.Pixel);
                // sourceBitmap.Dispose();

            }
        }

Write Code For UseCoordinates CheckBox Control CheckedChanged event:


private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (chkCoordinates.Checked == true)
            {
                txtCX1.Visible = true; lblCX1.Visible = true;
                txtCY1.Visible = true; lblCY1.Visible = true;
                txtCX2.Visible = true; lblCX2.Visible = true;
                txtCY2.Visible = true; lblCY2.Visible = true;
                txtDrawX1.Text = "0"; txtDrawX2.Text = "0"; txtDrawY1.Text = "0"; txtDrawY2.Text = "0";
            }
            else
            {
                txtCX1.Visible = false; lblCX1.Visible = false;
                txtCY1.Visible = false; lblCY1.Visible = false;
                txtCX2.Visible = false; lblCX2.Visible = false;
                txtCY2.Visible = false; lblCY2.Visible = false;
            }
        }

Write Code For "Save" button click event:


 private void btnSave_Click(object sender, EventArgs e)
        {
            targetBitmap.Save("CroppedImage.jpg", ImageFormat.Jpeg);
            MessageBox.Show("ImageSaved!");
        }

 

Cropping Image In C#