C#如何实现将图片转化为圆形图片
时间: 2023-08-14 19:08:33 浏览: 159
C#实现图片格式转换
4星 · 用户满意度95%
在C#中,可以通过以下步骤将一张图片转化为圆形图片:
1. 加载图片
使用`System.Drawing.Image.FromFile(string path)`方法加载图片,代码示例如下:
```csharp
string path = "image.jpg";
Image originalImage = Image.FromFile(path);
```
2. 创建画布
通过`System.Drawing.Graphics`类创建一个新的画布,并设置画布的宽度、高度和背景颜色,代码示例如下:
```csharp
int diameter = Math.Min(originalImage.Width, originalImage.Height);
Bitmap canvas = new Bitmap(diameter, diameter);
canvas.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
Graphics graphics = Graphics.FromImage(canvas);
graphics.Clear(Color.Transparent);
```
3. 绘制圆形
使用`System.Drawing.Drawing2D.GraphicsPath`类创建一个圆形路径,并将画布的剪辑区域设置为这个路径,代码示例如下:
```csharp
GraphicsPath path = new GraphicsPath();
path.AddEllipse(0, 0, diameter, diameter);
graphics.SetClip(path);
```
4. 绘制图片
将原始图片绘制到画布上,代码示例如下:
```csharp
int x = (diameter - originalImage.Width) / 2;
int y = (diameter - originalImage.Height) / 2;
graphics.DrawImage(originalImage, x, y);
```
5. 输出结果
将处理后的图片保存到本地或者输出到页面上,代码示例如下:
```csharp
string outputPath = "output.png";
canvas.Save(outputPath, ImageFormat.Png);
```
完整代码示例:
```csharp
string path = "image.jpg";
Image originalImage = Image.FromFile(path);
int diameter = Math.Min(originalImage.Width, originalImage.Height);
Bitmap canvas = new Bitmap(diameter, diameter);
canvas.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
Graphics graphics = Graphics.FromImage(canvas);
graphics.Clear(Color.Transparent);
GraphicsPath path = new GraphicsPath();
path.AddEllipse(0, 0, diameter, diameter);
graphics.SetClip(path);
int x = (diameter - originalImage.Width) / 2;
int y = (diameter - originalImage.Height) / 2;
graphics.DrawImage(originalImage, x, y);
string outputPath = "output.png";
canvas.Save(outputPath, ImageFormat.Png);
```
阅读全文