private void CreateImage(string codes)
{
try
{
int iMapWidth = codes.Length * 21;
Bitmap map = new Bitmap(iMapWidth, 28); //创建图片背景
Graphics graph = Graphics.FromImage(map);
graph.Clear(Color.AliceBlue);//清除画面,填充背景
graph.DrawRectangle(new Pen(Color.Black, 0), 0, 0, map.Width - 1, map.Height - 1);//画一个边框
graph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;//模式 抗锯齿
Random rand = new Random();
//背景噪点生成
Pen blackPen = new Pen(Color.LightGray, 0);
for (int i = 0; i < 50; i++)
{
int x = rand.Next(0, map.Width);
int y = rand.Next(0, map.Height);
graph.DrawRectangle(blackPen, x, y, 1, 1);
}
//验证码旋转,防止机器识别
char[] chars = codes.ToCharArray();//拆散字符串成单字符数组
//文字距中
StringFormat format = new StringFormat(StringFormatFlags.NoClip);
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
//定义颜色
Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
//定义字体
string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
for (int i = 0; i < chars.Length; i++)
{
int cindex = rand.Next(7);
int findex = rand.Next(5);
Font f = new System.Drawing.Font(font[findex], 13, System.Drawing.FontStyle.Bold);//字体样式(参数2为字体大小)
Brush b = new System.Drawing.SolidBrush(c[cindex]);
graph.DrawString(chars[i].ToString(), f, b, i*16+8, 15, format);
}
this.pictureBox1.Image = map;
}
catch (ArgumentException ex)
{
MessageBox.Show("创建图片验证码错误,错误原因:"+ex.Message.ToString());
}
}
/// <summary>
/// 得到单个字符
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
private string getOneCode(int a, int b)
{
char c = (char)ran.Next(a, b);
return c.ToString();
}
/// <summary>
/// 得到验证码
/// </summary>
/// <returns></returns>
private string getCode()
{
string code = "";
//Ascii码范围:数字:48-57,小写字母:97-122,大写字母:65-90
code += getOneCode(48,57);
code += getOneCode(97, 122);
code += getOneCode(65, 90);
code += getOneCode(97, 122);
code += getOneCode(48, 57);
return code;
}
/// <summary>
/// 加载验证码
/// </summary>
private void LoadCode()
{
string right_code = getCode();
CreateImage(right_code);
}