Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cut a part of image in C# [duplicate]

Tags:

c#

.net

graphics

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

like image 375
Friend Avatar asked Feb 28 '12 15:02

Friend


2 Answers

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);
like image 143
James Hill Avatar answered Nov 03 '22 01:11

James Hill


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);
like image 30
Abhijit Amin Avatar answered Nov 03 '22 00:11

Abhijit Amin