27

I have no idea how to cut a rectangle image from other big image.

Let's say there is 300 x 600 image.png.

I want just to cut a rectangle with X: 10 Y 20 , with 200, height 100 and save it into other file.

How I can do it in C#?

Thanks!!!

2
  • @Brian - post this as an answer (maybe with some quoted / referenced code) so we can vote it up.
    – RQDQ
    Feb 28, 2012 at 15:42
  • Does your image have transparent parts? Brian's link will not help if you need transparency, as bitmaps do not support it.
    – Msonic
    Feb 28, 2012 at 15:44

2 Answers 2

40

Check out the Graphics Class on MSDN.

Here's an example that will point you in the right direction (notice the Rectangle object):

public Bitmap CropImage(Bitmap source, Rectangle section)
{
    var bitmap = new Bitmap(section.Width, section.Height);
    using (var g = Graphics.FromImage(bitmap))
    {
        g.DrawImage(source, 0, 0, section, GraphicsUnit.Pixel);
        return bitmap;
    }
}

// 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);
33

Another way to corp an image would be to clone the image with specific starting points and size.

int x= 10, y=20, width=200, height=100;
Bitmap source = new Bitmap(@"C:\tulips.jpg");
Bitmap CroppedImage = source.Clone(new System.Drawing.Rectangle(x, y, width, height), source.PixelFormat);
4
  • 1
    This is a much better answer as it does not require to load an external assembly like Graphics in order to achieve the goal!
    – Andry
    Jan 26, 2017 at 9:39
  • After doing the clone, you can call the dispose() function of the source ( source.Dispose();) if you want to release any handles to the original bitmap. if you want to delete the original image for instance and keep only the cropped version, you will need to call the dispose() function prior delete the original image. just in case someone wants to do this operation.
    – Alexei
    Oct 18, 2017 at 3:16
  • Graphics solution is much faster than cloning, I'd prefer stay away from cloning bitmaps at all, since it is not a deep clone. And I'm unsure your dispose will work in this situation, both bitmaps will use same pixel data
    – Justas G
    Nov 9, 2017 at 19:59
  • 1
    how to do it for non-rectangle shape? I need to copy a trapezoid shape Mar 11, 2018 at 22:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.