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

2019-02-02 13:35发布

问题:

This question already has an answer here:

  • How to crop an image using C#? 14 answers

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

回答1:

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


回答2:

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


标签: c# .net graphics