Introduction for curious people
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.
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.Code:Bitmap croppedBitmap = new Bitmap(pictureBox1.Image);
My margins are provided by NumericUpDown controls, therefore I had to convert them from double to integer, which adds these "(int)" explicit conversions.
To show the results, my cropped image is put back into picturebox1. This is third code statement.Code:croppedBitmap = croppedBitmap.Clone(
new Rectangle(
(int)LeftMargin.Value, (int)TopMargin.Value,
(int)croppedBitmap.Width - (int)LeftMargin.Value - (int)RightMargin.Value,
(int)croppedBitmap.Height - (int)TopMargin.Value - (int)BottomMargin.Value),
System.Drawing.Imaging.PixelFormat.DontCare);
Output to show that it worksCode:pictureBox1.Image = croppedBitmap;
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: Cropping Images Prototype.zip
With regards to Siten, my old friend...


LinkBack URL
About LinkBacks









Reply With Quote










Bookmarks
Algorithms and Data Structures
Java tutorials
Algorithms Forum