
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.
Cropping an image is similar in operation.
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); |