学习笔记:利用GDI+生成简单的验证码图片
/// <summary>
/// 单击图片时切换图片
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pictureBox1_Click(object sender, EventArgs e)
{
Random r = new Random();
string str = string.Empty;
//生成5位随机数如 90531
for (int i = ; i < ; i++)
{
str += r.Next(, );
}
Bitmap bitmap = new Bitmap(, );
Graphics g = Graphics.FromImage(bitmap);
//预定义几种字体样式和颜色
string[] fonts = { "微软雅黑", "宋体", "黑体", "隶书", "仿宋" };
Color[] colors = { Color.Yellow, Color.Blue, Color.Black, Color.Red, Color.Orange };
//因为每一数字的字体和颜色可能不同,
//因此循环将生成的随机数每一数字绘制到图片
for (int i = ; i < str.Length; i++)
{
Point p = new Point(i * , );
g.DrawString(str[i].ToString(), new Font(fonts[r.Next(, )], , FontStyle.Bold), new SolidBrush(colors[r.Next(, )]), p);
}
//循环在图片范围内绘制出50条线
for (int i = ; i < ; i++)
{
//保证线的起始点都在图片范围内
Point p1 = new Point(r.Next(, bitmap.Width), r.Next(, bitmap.Height));
Point p2 = new Point(r.Next(, bitmap.Width), r.Next(, bitmap.Height));
g.DrawLine(new Pen(Brushes.Green), p1, p2);
}
//添加一些像素点
for (int i = ; i < ; i++)
{
Point p1 = new Point(r.Next(, bitmap.Width), r.Next(, bitmap.Height));
bitmap.SetPixel(p1.X, p1.Y, Color.Green);
}
//在winForm中用PictureBox中显示出来
pictureBox1.Image = bitmap;
}
最终效果如下