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. Commented 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. Commented 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); 
Sign up to request clarification or add additional context in comments.

Comments

35

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 Comments

This is a much better answer as it does not require to load an external assembly like Graphics in order to achieve the goal!
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.
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
how to do it for non-rectangle shape? I need to copy a trapezoid shape

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.