前言:现在的网页注册都使用验证码,原因是防止机器人注入。下面是自己写的一个验证码,分享给大家
源码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
public partial class 生成验证码_CheckCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CreateCodeImage(GenerateCheckCode());
}
//验证码
private string GenerateCheckCode()
{
Random rnd=new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 2; i++)
{
int number = rnd.Next(10);//得到0-9之间的随机数
char Bigletter = (char)rnd.Next('A', 'Z');//得到所有大写字母随机数
char Smallletter = (char)rnd.Next('a', 'z');//得到所有小写字母随机数
sb.Append(number.ToString() + Bigletter.ToString()+Smallletter.ToString());
}
return sb.ToString();
}
//生成随机图片
private void CreateCodeImage(string checkCode)
{
Bitmap image = new Bitmap((int)Math.Ceiling((checkCode.Length) * 12.5), 22);
Graphics g = Graphics.FromImage(image);
Font font = new Font("宋体", 15);//创建字体对象
LinearGradientBrush lgb = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.White, Color.Red, 1.2f, true);//创建填充对象 LinearGradientBrush属于System.Drawing.Drawing2D下
g.DrawString(checkCode, font, lgb, 2, 2);
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
MemoryStream ms = new MemoryStream();//创建器存储区为内存的流
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);//将图片以指定的图片形式保存到流中
Response.ClearContent();//清楚缓存中所有的内容输出
Response.ContentType = "Image/Gif";//设置流的输出类型
Response.BinaryWrite(ms.ToArray());//将流内容写入字节数组中并使用二进制写入客户端中
}
}