新建一个类用来创建验证码代码如下:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace UserCommon
{
public class validateCode
{
public string CreateCode(int length)
{
string Code = "";
Random r = new Random();
for (int i = 0; i < length; i++)
{
Code += r.Next(0, 9).ToString();
}
return Code;
}
//2.制作图片
public void CreateCodeImg(string code, HttpContext context)
{
//定义图片
Bitmap image = new Bitmap((int)Math.Ceiling(code.Length * 12.0), 22);
Graphics graphics = Graphics.FromImage(image);
//生成随机字体颜色
try
{
Random r = new Random();
graphics.Clear(Color.White);
//绘制线条
for (int i = 0; i < 10; i++)
{
int x1 = r.Next(image.Width);
int x2 = r.Next(image.Width);
int y1 = r.Next(image.Height);
int y2 = r.Next(image.Height);
graphics.DrawLine(new Pen(Color.Silver), x1, x2, y1, y2);
}
//绘制文本
Font font = new Font("微软雅黑", 12, (FontStyle.Bold | FontStyle