public partial class Admin_RandomImage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CreateCheckCode(GetCheckCode());
}
}
//生成随机数
/// <summary>
/// 生成随机验证码字符串
/// </summary>
/// <returns>生成的随机验证码字符串</returns>
private string GetCheckCode()
{
int number;
string code = string.Empty;//随机值种子
Random rd = new Random();
for (int i = 0; i < 4; i++)//验证码长度是4
{
number = rd.Next();
number = number % 36;
if (number < 10)
{
number += 48;
}
else
{
number += 55;
}
code += ((char)number).ToString();
}
Session["CheckCode"] = code;//在session中保存验证码
return code;
}
//画出验证码
/// <summary>
/// 根据验证码输出图片
/// </summary>
/// <param name="ccode">生成的随机验证码</param>
private void CreateCheckCode(string ccode)
{
//若验证码为空,则直接返回
if (ccode == null || ccode.Trim() == string.Empty)
{
return;
}
//根据验证码长度确定输出图片的长度
System.Drawing.Bitmap image = new System.Drawing.Bitmap(65, 30);
//创建Graphics对象
Graphics g = Graphics.FromImage(image);
try
{
//生成随机数种子
Random rd = new Random();
//清空图片背景颜色
g.Clear(Color.White);
//画图片的背景噪音线10条
//--------------------------------------------------------------------------
for (int i = 0; i < 10; i++)
{
//噪音线起点坐标(x1,y1),终点坐标(x2,y2)
int x1 = rd.Next(image.Width);
int x2 = rd.Next(image.Width);
int y1 = rd.Next(image.Height);
int y2 = rd.Next(image.Height);
//用蓝色画出噪音线
Pen p = new Pen(Color.Blue);
g.DrawLine(p, x1, y1, x2, y2);
}
//Brush b=Brushes.Silver;
//g.FillRectangle(b,0,0,image.Width,image.Height);
//验证码字体:15号Arial,粗斜体,下划线
Font f = new Font("Arial", 15, (FontStyle.Bold | FontStyle.Italic | FontStyle.Strikeout | FontStyle.Underline));
//线性渐变画刷
LinearGradientBrush lgb = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Black, Color.Purple, 1.2f, true);
g.DrawString(ccode, f, lgb, 2, 2);
//画图片的前噪音点100个
for (int i = 0; i < 100; i++)
{
int x = rd.Next(image.Width);
int y = rd.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(rd.Next()));
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Purple), 0, 0, image.Width - 1, image.Height - 1);
//创建内存流用于输出图片
using (MemoryStream ms = new MemoryStream())
{
//图片类型指定为PNG
image.Save(ms, ImageFormat.Png);
//清除缓冲区中的所有输出
Response.ClearContent();
//输出流HTTP MIME类型设置为:image/PNG
Response.ContentType = "image/png";
//输出图片的二进制流
Response.BinaryWrite(ms.ToArray());
}
}
finally
{
//释放Bitmap对象和Graphics对象
g.Dispose();
image.Dispose();
}
}
}
原文:http://blog.csdn.net/jin_guang/article/details/22284591