using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.IO;
namespace WebReport
{
public partial class CheckCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.ClearContent();
CheckCodeCreate();
}
//生成验证码的方法
public void CheckCodeCreate()
{
//定义可能出现的字符 及字符的颜色和字体的样式
char[] chars = { 'A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z',
'a','b','c','d','e','f','g','h','i','j','k','m','n','p','q','r','s','t','u','v','w','x','y','z',
'1','2','3','4','5','6','7','8','9'};
Color[] colors = { Color.Aqua,Color.AliceBlue, Color.Green, Color.Red, Color.Blue, Color.BlueViolet, Color.DeepPink, Color.MediumVioletRed, Color.Magenta, Color.Black, Color.Coral, Color.HotPink };
string[] fonts = { "宋体", "Castellar", "Arial", "Calibri", "Nina", "Raavi", };
Random rdm = new Random();
string code = string.Empty;
//生成一个4位数的随机数
for (int i = 0; i < 4; i++)
{
code += chars[rdm.Next(chars.Length)];
}
//将随机码存入Session中并转换为小写
this.Page.Session["CheckCode"] = code.ToLower();
//创建一个120*30的位图
using (Bitmap bitmap = new Bitmap(90, 30))
{
//创建一个画图的面板
using (Graphics g = Graphics.FromImage(bitmap))
{
//填充画板背景
g.Clear(Color.White);
//位图中生成100噪点
for (int i = 0; i < 100; i++)
{
bitmap.SetPixel(rdm.Next(90), rdm.Next(30), colors[rdm.Next(colors.Length)]);
}
//画板中所有的信息,包含字符,字体样式(大小),颜色字符写到画板上
for (int i = 0; i < code.Length; i++)
{
g.DrawString(code[i].ToString(),
new Font(fonts[rdm.Next(fonts.Length)], 18, FontStyle.Bold),
new SolidBrush(colors[rdm.Next(colors.Length)]),
new PointF(i * 22, 0)
);
}
//在画板中生成6条噪线
for (int i = 0; i <6; i++)
{
g.DrawLine(new Pen(Color.Blue,2 ), rdm.Next(90), rdm.Next(60), rdm.Next(90), rdm.Next(60));
}
// 画图的边框线
g.DrawRectangle(new Pen(Color.LightSkyBlue), 0, 0, bitmap.Width - 2, bitmap.Height - 2);
}
//将图片输出到客户端
using (MemoryStream ms = new MemoryStream())
{
Response.ClearContent();
Response.ContentType = "image/JPEG";
bitmap.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
Response.BinaryWrite(ms.ToArray());
Response.End();
}
}
}
}
}
在另一页面中调用方法 为:
<div>
验证码:<img alt="" src="CheckCode.aspx" id="imgcode" />
</div>
其中 CheckCode.aspx 为图片生成页面