直接把这个类复制出去就能使用
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
namespace 生成验证码
{
class CreateImage
{
public Image CrtImage(out string OutPutstr)
{
Bitmap bmp = new Bitmap(200, 50);
string str = "";
try
{
Random r = new Random();
char[] c = { 'A', 'v', 'd', 'Q', 'e', 'E', 'f', 'h', 'u', 'B' };
for (int i = 0; i < 5; i++)
{
int temp = r.Next(0, 10);
str += temp;
if (i % 2 == 0) str += c[temp]; / /这里 += 了3个字母
}
//图片中的字符串一共有8个字符
//创建画图对象
Graphics gp = Graphics.FromImage(bmp);
gp.Clear(Color.White);
string[] fonts = { "楷体", "宋体", "微软雅黑", "隶书", "黑体" };
Color[] color = { Color.Black, Color.Coral, Color.Green, Color.Aqua, Color.Red,Color.Beige,Color.Blue,Color.CadetBlue };
for (int i = 0; i < str.Length; i++)//在画布上面打印出多少个字符(应该与字符串的长度相等)
{
Point p = new Point(i * 20, i);
gp.DrawString(str[i].ToString(), new Font(fonts[r.Next(0, 5)], 20, FontStyle.Bold), new SolidBrush(color[r.Next(0, 8)]), p);
}
for (int i = 0; i < 100; i++) //绘制随机直线(直线不够多可以将循环次数改大点)
{
Point temp1 = new Point(r.Next(0, bmp.Width), r.Next(0, bmp.Width));
Point temp2 = new Point(r.Next(0, bmp.Width), r.Next(0, bmp.Width));
gp.DrawLine(new Pen(Color.Black), temp1, temp2);
}
for (int i = 0; i < 500; i++)//绘制像素颗粒(像素颗粒不够多可以将循环次数改大点)
{
Point p = new Point(r.Next(0, bmp.Width), r.Next(0, bmp.Height));
bmp.SetPixel(p.X, p.Y, Color.Red);
}
}
catch
{
OutPutstr = “”;// 发生异常返回空
return null;//
}
OutPutstr = str;
return bmp;//将图片赋值给控件(或者直接返回一个图片对象)
}
}
}