BLOG.CSHARPHELPER.COM: Crop a picture and save the result in C#
Crop a picture and save the result in C#
The program uses three Bitmap objects to hold different copies of the current image.
// The original image. private Bitmap OriginalImage;
// The currently cropped image. private Bitmap CroppedImage;
// The cropped image with the selection rectangle. private Bitmap DisplayImage; private Graphics DisplayGraphics;
OriginalImage holds the image originally loaded from the file.
CroppedImage holds the currently displayed bitmap as cropped without the selection rectangle.
DisplayImage holds the current image with the selection rectangle. DisplayGraphics is a Graphics object for drawing on DisplayImage. The program uses it to draw the selection rectangle.
The following code shows how the program lets you select an area.
// Let the user select an area. private bool Drawing = false; private Point StartPoint, EndPoint; private void picCropped_MouseDown(object sender, MouseEventArgs e) { Drawing = true; StartPoint = e.Location;
// Draw the area selected. DrawSelectionBox(e.Location); }
private void picCropped_MouseMove(object sender, MouseEventArgs e) { if (!Drawing) return;
// Draw the area selected. DrawSelectionBox(e.Location); }
// Crop. // Get the selected area's dimensions. int x = Math.Min(StartPoint.X, EndPoint.X); int y = Math.Min(StartPoint.Y, EndPoint.Y); int width = Math.Abs(StartPoint.X - EndPoint.X); int height = Math.Abs(StartPoint.Y - EndPoint.Y); Rectangle source_rect = new Rectangle(x, y, width, height); Rectangle dest_rect = new Rectangle(0, 0, width, height);
// Copy that part of the image to a new bitmap. DisplayImage = new Bitmap(width, height); DisplayGraphics = Graphics.FromImage(DisplayImage); DisplayGraphics.DrawImage(CroppedImage, dest_rect, source_rect, GraphicsUnit.Pixel);
// Display the new bitmap. CroppedImage = DisplayImage; DisplayImage = CroppedImage.Clone() as Bitmap; DisplayGraphics = Graphics.FromImage(DisplayImage); picCropped.Image = DisplayImage; picCropped.Refresh(); }
The MouseDown event handler saves the starting point, sets Drawing = true, and calls DrawSelectionBox. The MouseMove event handler updates the mouse's current point and calls DrawSelectionBox.
The MouseUp event handler finds the area selected. It makes a new Bitmap to fit the selected area and copies the selected part of the previous version of the image into the new bitmap. It then updates DisplayImage and CroppedImage.
This example uses code from the examples:
Comments