Cropping Images
The
Click event-handler for the
btnCrop button in the sample code shows how to crop an image. First, create an instance of an image object in the code and load the sample image file into an Image object. To crop the image, create a Bitmap instance containing the image data, and then create Rectangle objects with the source (
recCrop) and destination (
recDest) dimensions defined for the desired crop area. After creating the Bitmap and rectangles, you pass the Bitmap and rectangles to the Graphics class's
DrawImage method to draw the cropped image:
gphCrop.DrawImage(bmpImage, recDest,
recCrop.X, recCrop.Y,
recCrop.Width, recCrop.Height,
GraphicsUnit.Pixel);
Now you can save the cropped Bitmap as a new image file and load it into the picture box control on the form (see
Figure 1) as follows: .
bmpCrop.Save(Application.StartupPath +
cstrCropFileName);
pbImage.Image = bmpCrop;
 | |
| Figure 1: Sample image loaded into a PictureBox control on a form. |
Here's the complete code. Note how it uses the Bitmap, Rectangle, and Graphics objects to perform the cropping function.
private void btnCrop_Click(object sender,
System.EventArgs e)
{
const string cstrCropFileName =
"\\Crop_Sample.gif";
System.Drawing.Image img;
img = System.Drawing.Image.FromFile(strFileName);
Bitmap bmpImage = new Bitmap(img);
Rectangle recCrop = new Rectangle(0, 0,
bmpImage.Width/2, bmpImage.Height/2);
Bitmap bmpCrop = new Bitmap
(recCrop.Width/2, recCrop.Height/2,
bmpImage.PixelFormat);
Graphics gphCrop =
Graphics.FromImage(bmpCrop);
Rectangle recDest = new Rectangle(0, 0,
bmpImage.Width/2,bmpImage.Height/2);
gphCrop.DrawImage(bmpImage, recDest,
recCrop.X, recCrop.Y,
recCrop.Width, recCrop.Height,
GraphicsUnit.Pixel);
bmpCrop.Save(Application.StartupPath +
cstrCropFileName);
pbImage.Image = bmpCrop;
}