c#动态产生验证码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
//窗体登录事件产生验证码
//验证码的数值记录在number变量里面
//PictureBox1控件用来放验证码
using System;
using System.Collections.Generic;
using ponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using 实体类库_Model_;
using 业务逻辑层_BLL_;
namespace course5
{
public partial class loginform : Form
{
public static string number;
public loginform()
{
InitializeComponent();
}
//产生验证字符串、、、、
private string checkcode()
{
int num; // 保存产生的随机数
char code; // 保存随机数转换的字符
string check = "";//保存验证码
Random random = new Random();//随机数产生器
for (int i = 0; i < 4; i++)
{
num = random.Next();
if (num % 2 == 0)
code = (char)('0' + (char)(num % 10));
else
code = (char)('A' + (char)(num % 26));
check += "" + code.ToString();
}
return check;
}
private void codeimage(string checkcode)
{
if (checkcode == null || checkcode == "")
return;//产生位图参数:长度高度
Bitmap image = new Bitmap((int)Math.Ceiling(checkcode.Length * 12.5), 21);
Graphics g = Graphics.FromImage(image);
try
{
Random random = new Random();
g.Clear(Color.White);//白色背景
for (int i = 0; i <=5; i++)
{//画背景的黑色线
g.DrawLine(new Pen(Color.Black), random.Next(image.Width), random.Next(image.Width), random.Next(image.Height), random.Next(image.Height));
}
for (int i = 0; i <= 3; i++)
{//画背景的红色线
g.DrawLine(new Pen(Color.Red), random.Next(image.Width), random.Next(image.Width), random.Next(image.Height), random.Next(image.Height));
}
Font font = new Font("宋体", 12);
//验证码写到图片上
for (int i = 0; i < checkcode.Length; i++)
{
SizeF f = g.MeasureString(checkcode[i].ToString(), font);
//g.TranslateTransform(0.01f, 0);
Matrix m = g.Transform;
m.Shear(0.4f, 0.0f);
g.Transform = m;
g.DrawString(checkcode[i].ToString(), font, new SolidBrush(Color.Red), (f.Width - 8) * i - 5, 2);
} for (int i = 0; i < 100; i++)
{// 画噪黑色音点
image.SetPixel(random.Next(image.Width), random.Next(image.Height), Color.Black);
}
for (int i = 0; i < 80; i++)
{// 画噪红色音点
image.SetPixel(random.Next(image.Width), random.Next(image.Height), Color.Red);
}
// 截成矩形
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
this.pictureBox1.Height = image.Height;
this.pictureBox1.Width = image.Width;
this.pictureBox1.BackgroundImage = image;
}
catch
{
}
}
private void loginform_Load(object sender, EventArgs e)
{
//验证码
number = checkcode();
codeimage(number);
}
}
}