添加一个ashx文件,代码处理如下:
using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Web.SessionState;
public class RegisterImage : IHttpHandler ,IRequiresSessionState
{
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "image/gif";
//生成图片资源
Bitmap b = new Bitmap(130, 30);
Graphics g = Graphics.FromImage(b);
//画底框
g.FillRectangle(new SolidBrush(Color.DarkGray), 0, 0, 130, 30);
//设定字体
Font font = new Font(FontFamily.GenericSerif, 25, FontStyle.Bold, GraphicsUnit.Pixel);
//定义随机种子
Random r = new Random();
//设定验证码字符范围
string Letters = "abcdefghijklmnopqrstuvwxyz0123456789";
string letter;
StringBuilder StrBuilder = new StringBuilder();
using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Web.SessionState;
public class RegisterImage : IHttpHandler ,IRequiresSessionState
{
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "image/gif";
//生成图片资源
Bitmap b = new Bitmap(130, 30);
Graphics g = Graphics.FromImage(b);
//画底框
g.FillRectangle(new SolidBrush(Color.DarkGray), 0, 0, 130, 30);
//设定字体
Font font = new Font(FontFamily.GenericSerif, 25, FontStyle.Bold, GraphicsUnit.Pixel);
//定义随机种子
Random r = new Random();
//设定验证码字符范围
string Letters = "abcdefghijklmnopqrstuvwxyz0123456789";
string letter;
StringBuilder StrBuilder = new StringBuilder();
//随机生成显示的字母组合,存放在StrBuilder中
for (int x = 0; x < 5; ++x)
{
letter = Letters.Substring(r.Next(0, Letters.Length - 1), 1);
StrBuilder.Append(letter);
g.DrawString(letter, font, new SolidBrush(Color.Black), x * 25, r.Next(0, 5));
}
Pen linePen = new Pen(new SolidBrush(Color.Gray), 2);
for (int x = 0; x < 5; ++x)
{
letter = Letters.Substring(r.Next(0, Letters.Length - 1), 1);
StrBuilder.Append(letter);
g.DrawString(letter, font, new SolidBrush(Color.Black), x * 25, r.Next(0, 5));
}
Pen linePen = new Pen(new SolidBrush(Color.Gray), 2);
//添加横线
for (int x = 0; x < 3; ++x)
g.DrawLine(linePen, new Point(r.Next(0, 129), r.Next(0, 29)), new Point(r.Next(100, 129), r.Next(0, 29)));
//生成gif文件到客户端应答
b.Save(context.Response.OutputStream, ImageFormat.Gif);
//写入会话
context.Session["SecurityCode"] = StrBuilder.ToString();
context.Response.End();
}
public bool IsReusable
{
get {
return true;
}
}
}
for (int x = 0; x < 3; ++x)
g.DrawLine(linePen, new Point(r.Next(0, 129), r.Next(0, 29)), new Point(r.Next(100, 129), r.Next(0, 29)));
//生成gif文件到客户端应答
b.Save(context.Response.OutputStream, ImageFormat.Gif);
//写入会话
context.Session["SecurityCode"] = StrBuilder.ToString();
context.Response.End();
}
public bool IsReusable
{
get {
return true;
}
}
}
需要使用的时候,在页面添加img标签,在src引用该ashx文件就可以喇。