26

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!!!

NoWar
  • 36,338
  • 80
  • 323
  • 498
  • @Brian - post this as an answer (maybe with some quoted / referenced code) so we can vote it up. – RQDQ Feb 28 '12 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 '12 at 15:44

2 Answers2

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);
Jerry Nixon
  • 31,313
  • 14
  • 117
  • 233
James Hill
  • 60,353
  • 20
  • 145
  • 161
32

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);
Abhijit Amin
  • 541
  • 4
  • 9
  • 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 '17 at 09: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 '17 at 03: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 09 '17 at 19:59
  • 1
    how to do it for non-rectangle shape? I need to copy a trapezoid shape – Kulpemovitz Mar 11 '18 at 22:18