C#生成图片验证码的代码
时间: 2023-07-12 22:04:36 浏览: 58
以下是一个简单的 C# 代码示例,用于生成数字验证码图像:
```csharp
using System;
using System.Drawing;
using System.Drawing.Imaging;
namespace ImageVerificationCode
{
public class VerificationCodeGenerator
{
public Bitmap GenerateVerificationCode(int length, int width, int height)
{
Random random = new Random();
string verificationCode = string.Empty;
for (int i = 0; i < length; i++)
{
verificationCode += random.Next(0, 9).ToString();
}
Bitmap bitmap = new Bitmap(width, height);
Graphics graphics = Graphics.FromImage(bitmap);
graphics.Clear(Color.White);
Font font = new Font("Arial", 20, FontStyle.Bold);
Brush brush = new SolidBrush(Color.Black);
graphics.DrawString(verificationCode, font, brush, 10, 10);
for (int i = 0; i < 100; i++)
{
int x1 = random.Next(width);
int y1 = random.Next(height);
int x2 = random.Next(width);
int y2 = random.Next(height);
Pen pen = new Pen(Color.Black);
graphics.DrawLine(pen, x1, y1, x2, y2);
}
return bitmap;
}
}
}
```
使用方法:
```csharp
VerificationCodeGenerator generator = new VerificationCodeGenerator();
Bitmap bitmap = generator.GenerateVerificationCode(4, 120, 40);
bitmap.Save("verification_code.bmp", ImageFormat.Bmp);
```
这将生成一个长度为4,宽120像素,高40像素的位图,并将其保存为BMP格式的图像文件。