在C#中,可以使用System.Drawing命名空间中的Graphics类和Bitmap类来进行图片剪裁。以下是一个简单的示例代码,演示如何使用Graphics类和Bitmap类进行图片剪裁。
首先,我们需要创建一个Bitmap对象,它将作为待剪裁的源图像。可以使用以下代码将图像加载到Bitmap对象中:
```csharp
using System.Drawing;
Bitmap sourceImage = new Bitmap("sourceImage.jpg");
```
接下来,我们需要创建一个新的Bitmap对象,它将作为剪裁后的目标图像。可以使用以下代码来创建新的Bitmap对象:
```csharp
Bitmap targetImage = new Bitmap(width, height);
```
在以上代码中,width和height是指要剪裁的图像的宽度和高度。
接下来,我们需要创建一个Graphics对象,用于在目标图像上绘制剪裁后的图像:
```csharp
Graphics g = Graphics.FromImage(targetImage);
```
以下是两种不同的剪裁方式:
1. 矩形剪裁
如果要进行矩形剪裁,可以使用Graphics类的DrawImage方法:
```csharp
Rectangle cropRectangle = new Rectangle(x, y, width, height);
g.DrawImage(sourceImage, 0, 0, cropRectangle, GraphicsUnit.Pixel);
```
在以上代码中,cropRectangle指定了要剪裁的矩形区域的位置和大小,x和y是矩形的左上角坐标。
2. 不规则剪裁
如果要进行不规则剪裁,可以创建一个GraphicsPath对象,并在其中添加一个由若干个点组成的路径,然后使用Graphics类的FillPath方法来剪裁图像:
```csharp
GraphicsPath path = new GraphicsPath();
path.AddPolygon(pointsArray);
g.Clip = new Region(path);
g.DrawImage(sourceImage, new Rectangle(0, 0, targetImage.Width, targetImage.Height), cropRectangle, GraphicsUnit.Pixel);
```
在以上代码中,pointsArray是一个PointF类型的数组,用于指定不规则路径的顶点。cropRectangle是指定源图像中要剪裁的矩形区域的位置和大小。
完整示例代码:
```csharp
using System.Drawing;
// 矩形剪裁
public static Bitmap CropRectangle(Bitmap sourceImage, int x, int y, int width, int height)
{
Bitmap targetImage = new Bitmap(width, height);
Graphics g = Graphics.FromImage(targetImage);
Rectangle cropRectangle = new Rectangle(x, y, width, height);
g.DrawImage(sourceImage, 0, 0, cropRectangle, GraphicsUnit.Pixel);
return targetImage;
}
// 不规则剪裁
public static Bitmap CropPolygon(Bitmap sourceImage, PointF[] pointsArray)
{
Bitmap targetImage = new Bitmap(sourceImage.Width, sourceImage.Height);
Graphics g = Graphics.FromImage(targetImage);
GraphicsPath path = new GraphicsPath();
path.AddPolygon(pointsArray);
g.Clip = new Region(path);
g.DrawImage(sourceImage, new Rectangle(0, 0, targetImage.Width, targetImage.Height), new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), GraphicsUnit.Pixel);
return targetImage;
}
```
以上代码中,我们定义了两个函数:CropRectangle和CropPolygon。CropRectangle函数接受一个Bitmap对象和要剪裁的矩形区域的位置和大小,返回剪裁后的图像。CropPolygon函数接受一个Bitmap对象和不规则路径的顶点数组,返回剪裁后的图像。
注意,这些函数只适用于小型图像。对于大型图像或需要进行高精度剪裁的图像,需要使用其他的方法进行剪裁。
- EOF -
技术群:添加小编微信dotnet999
公众号:Dotnet讲堂