随机验证码

   

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GDI_
{
public partial class 数字母 : Form
{
public 数字母()
{
InitializeComponent();
}
//在WinForm窗体在实现随机验证码
private void pictureBox1_Click(object sender, EventArgs e)
{
//定义画布大小
Bitmap bmp = new Bitmap(100, 100);
//定义一个变量
string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
Random r = new Random (); //随机生成
string newstr = "";
for(int i=0;i<6;i++)
{
newstr += str[r.Next(0, 62)];
}
Graphics g = Graphics.FromImage(bmp);
//随机字体
String[] fname = { "仿宋", "黑体", "宋体", "楷体", "微软雅黑", "华文行楷" };
//随机颜色

Color[] color = { Color.Red, Color.Green, Color.Pink, Color.Yellow, Color.Gold, Color.Black };
for(int i=0;i<newstr.Length;i++)
{
Point p = new Point(i * 15, 20);
g.DrawString(newstr[i].ToString(), new Font(fname[r.Next(0, 6)], 18, FontStyle.Italic), new SolidBrush(color[r.Next(0, 6)]), p);
}
// 验证码上画图片的背景噪音线
for (int i=0;i<15;i++)
{
g.DrawLine(new Pen(color[r.Next(0, 6)]), new Point(r.Next(0, 100), r.Next(0, 100)), new Point(r.Next(0, 100), r.Next(0, 100)));
}
// 验证码上画图片的背景噪音点
for (int i=0;i<300;i++)
{
bmp.SetPixel(r.Next(0, 100), r.Next(0, 100), color[r.Next(0, 6)]);
}
this.pictureBox1.Image = bmp;
}

原文地址:https://www.cnblogs.com/-zhang1995/p/7780304.html