代码片:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 绘制验证码
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string str = null;
private void pictureBox1_Click(object sender, EventArgs e)
{
str = null;
CreateMap();
}
/// <summary>
/// 绘制验证码图形
/// </summary>
void CreateMap()
{
//随机产生5个随机数
Random r = new Random();
//创建一个位图放在picturebox中
Bitmap bitmap = new Bitmap(100, 40);
Graphics g = Graphics.FromImage(bitmap);
pictureBox1.Image = bitmap;
pictureBox1.BorderStyle = BorderStyle.FixedSingle;
string[] fonts = { "微软雅黑", "宋体", "黑体", "隶书", "仿宋" };
Color[] colors = { Color.Purple, Color.Blue, Color.Black, Color.Red, Color.Green };
//将随机产生的数字放入bitmap中
for (int i = 0; i < 5; i++)
{
int number = r.Next(0, 10);
Point point = new Point(i * 20, 0);
g.DrawString(number.ToString(), new Font(fonts[r.Next(0, 5)], 20, FontStyle.Bold), new SolidBrush(colors[r.Next(0, 5)]), point);
str += number.ToString();
}
//随机绘制直线
for (int i = 0; i < 40; i++)
{
Pen pen = new Pen(new SolidBrush(colors[r.Next(0, 5)]));
Point p1 = new Point(r.Next(0,bitmap.Width),r.Next(0,bitmap.Height));
Point p2 = new Point(r.Next(0,bitmap.Width),r.Next(0,bitmap.Height));
g.DrawLine(pen,p1,p2);
}
//随机画像素点
for (int i = 0; i < 200; i++)
{
Point point = new Point(r.Next(0,bitmap.Width),r.Next(0,bitmap.Height));
bitmap.SetPixel(point.X, point.Y, colors[r.Next(0, 5)]);
}
}
private void Form1_Load(object sender, EventArgs e)
{
CreateMap();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == str)
{
MessageBox.Show("验证成功!");
}
else
{
MessageBox.Show("验证码输入有误,请重新输入");
}
}
}
}
实现效果: