您的位置:首页 > 编程语言 > C#

c#生成图片验证码

2015-07-19 16:17 337 查看
一般处理程序 ashx :它没有服务器控件,用response输出什么就是什么,一般作为文件来使用,放在aspx页面里使用

session:是用来存储数据的,设计一个服务器端的全局变量,在一般处理程序中,使用session需要引用命名空间,并继承接口

imagebutton用来显示验证码图片,通过?id=...来改变图片

一般处理程序ashx里的代码

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;
using System.Drawing;
using System.Web.SessionState;
//引用的命名空间
public class Handler : IHttpHandler, IRequiresSessionState
{
public string charSet = "2,3,4,5,6,8,9,A,B,C,D,E,F,G,H,J,K,M,N,P,R,S,U,W,X,Y";
public void ProcessRequest (HttpContext context)
{

string validateCode = CreateRandomCode(4);
context.Session["ValidateCode"] = validateCode;
CreateImage(validateCode, context);

//context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
//string validateCode = CreateRandomCode(4);
//context.Session["ValidateCode"] = validateCode;
//CreateImage(validateCode, context);

}

public bool IsReusable
{
get
{
return false;
}
}

private string CreateRandomCode(int n)
{
string[] CharArray = charSet.Split(',');
string randomCode = "";
int temp = -1;
Random rand = new Random();
for (int i = 0; i < n; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
} int t = rand.Next(CharArray.Length - 1);
if (temp == t)
{
return CreateRandomCode(n);
} temp = t;
randomCode += CharArray[t];
}
return randomCode;
}

//绘制验证码图片
private void CreateImage(string checkCode, HttpContext context)
{
int iwidth = (int)(checkCode.Length * 13);
System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 23);
Graphics g = Graphics.FromImage(image);
Font f = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Italic | System.Drawing.FontStyle.Bold));        // 前景色

Brush b = new System.Drawing.SolidBrush(Color.Black);        // 背景色
g.Clear(Color.White);        // 填充文字
g.DrawString(checkCode, f, b, 0, 1);        // 随机线条
Pen linePen = new Pen(Color.Gray, 0);
Random rand = new Random();
for (int i = 0; i < 5; i++)
{
int x1 = rand.Next(image.Width);
int y1 = rand.Next(image.Height);
int x2 = rand.Next(image.Width);
int y2 = rand.Next(image.Height);
g.DrawLine(linePen, x1, y1, x2, y2);
}
// 随机点
for (int i = 0; i < 30; i++)
{
int x = rand.Next(image.Width);
int y = rand.Next(image.Height);
image.SetPixel(x, y, Color.Gray);
}
// 边框
g.DrawRectangle(new Pen(Color.Gray), 0, 0, image.Width - 1, image.Height - 1);
// 输出图片
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
context.Response.ClearContent();
context.Response.ContentType = "image/Jpeg";
context.Response.BinaryWrite(ms.ToArray());

g.Dispose();
image.Dispose();
}

}


aspx里的代码

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;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text.ToUpper().Trim() == Session["ValidateCode"].ToString().ToUpper().Trim())
{
Response.Write("<script>alert('验证码相同')</script>");
}
else
{
Response.Write("<script>alert('验证码不正确')</script>");
}

}
//看不清,换一张
protected void Button2_Click(object sender, EventArgs e)
{
//通过超链接传值来改变验证码图片
ImageButton1.ImageUrl = "Handler.ashx?id="+new Random().Next(62);
}
}


aspx界面里的代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>
<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

<br />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="登录" />

<br />
<br />
 <br />
  
<asp:Label ID="Label1" runat="server" Text="验证码"></asp:Label>
  
<asp:TextBox ID="TextBox1" runat="server" Height="32px"></asp:TextBox>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="看不清 换一张" />

重点看这一句
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="Handler.ashx" />

</ContentTemplate>
</asp:UpdatePanel>
    
 

<br />
<br />
<br />
<br />
                      

</div>
</form>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: