Crop Image – C# and VB.NET
Posted on May 24th, 2010 in C#, VB.NET | 5 Comments »
For cropping an image in C# & VB.NET we can use the Graphics class. We’ll use a method (or function in VB.NET) which will take 2 parameters, a source image and a rectangle of the section that should be cropped. Let’s code!
The Code
C#:
public Bitmap CropImage(Bitmap source, Rectangle section)
{
// An empty bitmap which will hold the cropped image
Bitmap bmp = new Bitmap(section.Width, section.Height);
Graphics g = Graphics.FromImage(bmp);
// Draw the given area (section) of the source image
// at location 0,0 on the empty bitmap (bmp)
g.DrawImage(source, 0, 0, section, GraphicsUnit.Pixel);
return bmp;
}
// Example use:
Bitmap source = new Bitmap(@"C:\tulips.jpg");
Rectangle section = new Rectangle(new Point(12, 50), new Size(150, 150));
Bitmap CroppedImage = CropImage(source, section);
VB.NET
Function CropImage(ByVal source As Bitmap, ByVal section As Rectangle) As Bitmap
' An empty bitmap which will hold the cropped image
Dim bmp As New Bitmap(section.Width, section.Height)
Dim g As Graphics = Graphics.FromImage(bmp)
' Draw the given area (section) of the source image
' at location 0,0 on the empty bitmap (bmp)
g.DrawImage(source, 0, 0, section, GraphicsUnit.Pixel)
return bmp
End Function
' Example use:
Dim source As New Bitmap("C:\tulips.jpg")
Dim section As New Rectangle(new Point(12, 50), new Size(150, 150))
Dim CroppedImage As Bitmap = CropImage(source, section)
Explanation
The above code will work perfectly but it seems confusing, doesn’t it? You might have been wondering how it works. Well…
We first make an empty bitmap of the same width/height as the section rectangle. This bitmap will hold the cropped image. We use the section rectangle’s width/height because it determines the size of the cropped image. Then we use the Graphics class’s DrawImage() method (function) for the cropping. It draws the given area (section) of the source image on the empty bitmap and that’s it. The empty bitmap now holds the cropped image.
Source Code
Download Source Code for VB.NET
If you have any questions, don’t hesitate to post a comment.
Thanks
