如何在C#中剪切图像的一部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9484935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:36:28  来源:igfitidea点击:

How to cut a part of image in C#

c#.netgraphics

提问by Developer

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

我不知道如何从其他大图像中剪切矩形图像。

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

假设有300 x 600 image.png。

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

我只想用X: 10 Y 20 ,200,高度 100切割一个矩形并将其保存到其他文件中。

How I can do it in C#?

我如何在 C# 中做到这一点?

Thanks!!!

谢谢!!!

采纳答案by James Hill

Check out the Graphics Classon MSDN.

查看MSDN 上的图形类

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

这是一个示例,它将为您指明正确的方向(注意Rectangle对象):

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

回答by Abhijit Amin

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