Changing resolution or cropping an image

 

One of the simpler processes in GDI+ image manipulation is changing the resolution of an image or cropping an image. This all depends on the DrawImage method as illustrated in the GDI+ FAQ article "Drawing an image" which you may wish to read before continuing.

 

To change the resolution of an image you need to go through the following steps.

  • Load the original image
  • Create a blank image of the resolution you desire.
  • Get a Graphics object for the new image
  • Draw the original image onto the new one
  • Save the new image, perhaps with a different filename.

 

Cropping an image is similar in operation.

  • Load the original image
  • Create a blank image the same size as the area you want to crop to
  • Get the Graphics object for the new image
  • Draw the desired portion of the original image onto the new image
  • Save the new image, perhaps with a different filename.

 

Listing 1 shows how to change the resolution of an image to make it 30% of the original's width and height.

 

Bitmap bm = (Bitmap)Image.FromFile("myimage.jpg");

Bitmap resized = new Bitmap((int)(0.3f*bm.Width),(int)(0.3f*bm.Height));

Graphics g=Graphics.FromImage(resized);

g.DrawImage(bm, new Rectangle(0,0,resized.Width,resized.Height),0,0,bm.Width,bm.Height,GraphicsUnit.Pixel);

g.Dispose();

resized.Save("resizedimage.jpg",ImageFormat.Jpeg);

 

Listing 2 shows how to crop an image..

 

Bitmap bm = (Bitmap)Image.FromFile("myimage.jpg"); // assumes a 400 * 300 image from which a 160 * 120 chunk will be taken

Bitmap cropped = new Bitmap(160,120);

Graphics g=Graphics.FromImage(cropped);

g.DrawImage(bm, new Rectangle(0,0,cropped.Width,cropped.Height),100,50,cropped.Width,cropped.Height,GraphicsUnit.Pixel);

g.Dispose();

cropped.Save("croppedimage.jpg",ImageFormat.Jpeg);

 

 Return to the GDI+ FAQ