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

随机产生验证码图片---参考代码

2015-03-11 11:29 316 查看
前端:

<tr>
<td style="height: 20px" ><div align="center"> 验证码:</div></td>
<td align="left" style="width: 277px; height: 20px;" ><asp:TextBox ID="txtCode" runat="server" Height="25px" Width="112px"></asp:TextBox></td>
<td align="center" style="height: 20px" ><asp:Image ID="Image1" runat="server" Width="100px" BorderColor="Gray" BorderWidth="1px" Height="32px" ImageUrl="~/Image.aspx" /></td>
<td align="center" style="height: 20px" ><asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtCode"
Display="Dynamic" ErrorMessage="请输入验证码" ForeColor="DimGray" Font-Size="10pt">*</asp:RequiredFieldValidator>
 </td>
</tr>


Image.aspx

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>

</div>
</form>
</body>
</html>


Image.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;
public partial class Image : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string tmp = RndNum(Convert.ToInt16(6));
Session["verify"] = tmp;
ValidateCode(tmp);
}
private void ValidateCode(string VNum)
{
Bitmap Img = null;
Graphics g = null;
MemoryStream ms = null;
int gheight = VNum.Length * 9;
Img = new Bitmap(gheight, 18);
g = Graphics.FromImage(Img);
//背景颜色
g.Clear(Color.WhiteSmoke);
//文字字体
Font f = new Font("Tahoma", 10);
//文字颜色
SolidBrush s = new SolidBrush(Color.Red);
g.DrawString(VNum, f, s, 3, 3);
ms = new MemoryStream();
Img.Save(ms, ImageFormat.Jpeg);
Response.ClearContent();
Response.ContentType = "image/Jpeg";
Response.BinaryWrite(ms.ToArray());
g.Dispose();
Img.Dispose();
Response.End();
}
private string RndNum(int VcodeNum)
{
string MaxNum = "";
string MinNum = "";
for (int i = 0; i < 5; i++)//这里的4是验证码的位数
{
MaxNum = MaxNum + "5";
}
MinNum = MaxNum.Remove(0, 1);
Random rd = new Random();
string VNum = Convert.ToString(rd.Next(Convert.ToInt32(MinNum), Convert.ToInt32(MaxNum)));
return VNum;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: