驗證碼
<title>驗證碼</title>
<script type="text/javascript">
//点击切换验证码
function f_refreshtype() {
var Image1 = document.getElementById("img");
if (Image1 != null) {
Image1.src = Image1.src + "?";
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<span>--------------------驗證碼1--------------------</span>
<div>
<span id="identifyingCode">驗證碼:</span>
<input id="txtCode" type="text" />
<!----javascript:var time = new Date().getTime(); this.src=this.src + '?' + time;//點擊換驗證碼----->
<img src="IdentifyingCode.aspx"
style="vertical-align:bottom; margin-bottom:1px; cursor: pointer;"
alt="点击刷新" onclick="javascript:var time = new Date().getTime(); this.src=this.src + '?' + time;"/>
</div>
<div>
<span>--------------------驗證碼2--------------------</span>
<table>
<tr>
<td>
<span >驗證碼:</span><input id="TextBox1" type="text" runat="server" />
</td>
<td>
<img src="png.aspx" id="img" onclick="f_refreshtype()" />
</td>
<td>
<asp:Button ID="Button1" runat="server" Text="确定" />
</td>
</tr>
</table>
</div>
</div>
</form>
</body>
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace _5._15Practice
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string randomcode = this.CreateRandomCode(4);
Response.Cookies.Add(new HttpCookie("CheckCode", randomcode));
//ViewState["ValidateCode"] = randomcode; // Session、Cookie、ViewState都可保存,根据实际情况定
this.CreateImage(randomcode);
}
#region 生成一定长度的验证码
/// <summary>
/// 生成随机码
/// </summary>
/// <param name="length">随机码个数</param>
/// <returns></returns>
private string CreateRandomCode(int length)
{
int rand;
char code;
string randomcode = String.Empty;
//生成一定长度的验证码
System.Random random = new Random();
for (int i = 0; i < length; i++)
{
rand = random.Next();
if (rand % 3 == 0)
{
code = (char)('A' + (char)(rand % 26));
}
else
{
code = (char)('0' + (char)(rand % 10));
}
randomcode += code.ToString();
}
return randomcode;
}
#endregion
#region 创建随机码图片
/// <summary>
/// 创建随机码图片
/// </summary>
/// <param name="randomcode">随机码</param>
private void CreateImage(string randomcode)
{
int randAngle = 45; //随机转动角度
int mapwidth = (int)(randomcode.Length * 16);
Bitmap map = new Bitmap(mapwidth, 28); //创建图片背景,设置其长宽
Graphics graph = Graphics.FromImage(map);//繪圖圖面
graph.Clear(Color.AliceBlue);//清除繪圖面,并用指定顔色填充
graph.DrawRectangle(new Pen(Color.Black, 0), 0, 0, map.Width - 1, map.Height - 1);//画一个边框
Random rand = new Random();//隨機數生成器
#region 生成背景噪点
// 生成背景噪点
Pen blackPen = new Pen(Color.LightGray, 0);//定義一個畫筆
for (int i = 0; i < 200; i++)//噪點個數
{
int x = rand.Next(0, map.Width);
int y = rand.Next(0, map.Height);
graph.DrawRectangle(blackPen, x, y, 1, 1);//隨機分佈
}
#endregion
#region 验证码旋转,防止机器识别
//验证码旋转,防止机器识别
char[] chars = randomcode.ToCharArray();//拆散字符串成单字符数组
//文字距中
///封裝文本佈局信息--文字距中
StringFormat format = new StringFormat(StringFormatFlags.NoClip);
format.Alignment = StringAlignment.Center;//水平對齊方式
format.LineAlignment = StringAlignment.Center;//垂直對齊方式
/// 定义随机颜色列表
Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
/// 定义随机字体字体
string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
for (int i = 0; i < chars.Length; i++)
{
///顔色下標
int cindex = rand.Next(7);
///字體下標
int findex = rand.Next(5);
///設定文本格式
Font f = new System.Drawing.Font(font[findex], 16, System.Drawing.FontStyle.Bold); // 字体样式(第二参数为字体大小)
Brush b = new System.Drawing.SolidBrush(c[cindex]);
Point dot = new Point(11, 11); // 括号内数值越大,字符间距越大
float angle = rand.Next(0, randAngle); // 转动的度数,如果将0改为-randAngle,那么旋转角度为-45度~45度
graph.TranslateTransform(dot.X, dot.Y);
graph.RotateTransform(angle);
graph.DrawString(chars[i].ToString(), f, b, 2, 6, format); // 第4、5个参数控制左、上间距
graph.RotateTransform(-angle);
graph.TranslateTransform(2, -dot.Y);
}
#endregion
//生成图片
System.IO.MemoryStream ms = new System.IO.MemoryStream();
map.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "image/gif";
Response.BinaryWrite(ms.ToArray());
graph.Dispose();
map.Dispose();
}
#endregion
}
}