Crop Image – C# and VB.NET

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 C#

Download Source Code for VB.NET

If you have any questions, don’t hesitate to post a comment.

Thanks

7 thoughts on “Crop Image – C# and VB.NET

  1. You need to explain where exactly people are supposed to place the code parts…you are just dropping code blindly and not telling us where to place the code…even better, just include the project file as a download…you can easily use MEGAUPLOAD or RAPIDSHARE….this saves people headaches.

    • I always assume the reader will have basic knowledge of C# / VB.NET. That is why I don’t explain where to place the code because its pretty simple.

      I’ve edited the post. You can download the source code now.

    • Sorry, I don’t have Vs2005.

      Download the source code. And make a new project in Vs2005 and copy the code from the “.cs” files.

  2. Hello, currently I’m learning to program c# for image processing. I’ve tried your source code but it seems to not working. Here’s my code and please correct me. Thank you.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;

    namespace WindowsFormsApplication1
    {
    public partial class Form1 : Form
    {
    public Bitmap CropImage(Bitmap source, Rectangle section)
    {
    Bitmap bmp = new Bitmap(section.Width, section.Height);

    Graphics g = Graphics.FromImage(bmp);

    g.DrawImage(source, 0, 0, section, GraphicsUnit.Pixel);

    return bmp;
    }

    public Form1()
    {
    InitializeComponent();
    }

    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
    string Chosen_File = “”;

    openFD.InitialDirectory = “C:”;
    openFD.Title = “Insert Image”;
    openFD.FileName = “”;
    openFD.Filter = “JPEG Images|*.jpg|GIF Images|*.gif|BITMAPS|*.bmp|All Files|*.*”;

    if (openFD.ShowDialog() == DialogResult.Cancel)
    {
    MessageBox.Show(“Cancel?”);

    }
    else
    {

    Chosen_File = openFD.FileName;
    pictureBox1.Image = Image.FromFile(Chosen_File);
    }

    }

    private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
    {
    string Saved_File = “”;
    saveFileDialog.DefaultExt = “jpg”;
    saveFileDialog.Filter = “JPEG Images|*.jpg|GIF Images|*.gif|BITMAPS|*.bmp|All Files|*.*”;
    saveFileDialog.AddExtension = true;
    saveFileDialog.RestoreDirectory = true;
    saveFileDialog.Title = “Where do you want to save the file?”;
    saveFileDialog.FileName = “”;
    saveFileDialog.InitialDirectory = “C:\\”;

    if (saveFileDialog.ShowDialog() == DialogResult.OK)
    {
    Saved_File = saveFileDialog.FileName;
    MessageBox.Show(“You selected the file: ” + Saved_File);
    try
    {
    pictureBox1.Image.Save(Saved_File);
    }
    catch (Exception f)
    {
    MessageBox.Show(f.Message);
    }
    }
    else
    {
    MessageBox.Show(“Cancel or closed the dialog.”);
    }
    }

    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
    if (MessageBox.Show(“Seriously quitting?? :( “, “Exit”, MessageBoxButtons.OKCancel) == DialogResult.OK)

    Application.Exit();
    }

    private void pictureBox1_Click(object sender, EventArgs e)
    {
    pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;

    }

    private void cropToolStripMenuItem_Click(object sender, EventArgs e)
    {
    Bitmap img = new Bitmap(pictureBox1.Image);

    // The section that will be cropped.
    Rectangle section = new Rectangle(10, 10, 100, 100);

    // Crop the image and save it
    img = CropImage(img, section);
    img.Save(“C:\\test.jpg”);

    }
    }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>