I got a nice homework assignment from Siten, to make a program that crops images. It seemed easy at first, but then ...proven otherwise. Therefore let me show you some code that "cuts margins off images", or how Photoshop names it: crops images.
Cropping an image (or bitmap)
First of all, you can only crop a Bitmap class. If you have an Image class, you will have to transform it to a Bitmap object. This is my first code statement.
Bitmap croppedBitmap = new Bitmap(pictureBox1.Image);
Cropping a Bitmap may seem hard to implement, probably because it is being done by cloning... yes, Clone() method takes optional arguments that can be smaller than original image. This is second code statement.
My margins are provided by NumericUpDown controls, therefore I had to convert them from double to integer, which adds these "(int)" explicit conversions.
croppedBitmap = croppedBitmap.Clone(
(int)croppedBitmap.Width - (int)LeftMargin.Value - (int)RightMargin.Value,
(int)croppedBitmap.Height - (int)TopMargin.Value - (int)BottomMargin.Value),
To show the results, my cropped image is put back into picturebox1. This is third code statement.
pictureBox1.Image = croppedBitmap;
Output to show that it works
Here are screenshots showing two subsequent cropping done on a picture made by NASA.
Code behind this prototype
You can open the whole solution and play with it as you want. Also you can run a compiled exe without using Visual Studio, just look into Bin\Release\ folder.
Solution code: [ATTACH]1909[/ATTACH]
With regards to Siten, my old friend...
Edited by ArekBulski, 14 August 2009 - 04:52 PM.