语音验证码----软件设计人性化的体现

今日偶然的机会做一个语音验证码控件,网上张罗之后,IT云飞扬的开源代码很有参考价值,特此列出,大家互相,将开源进行到底。

页面截图:



页面上放置验证码图片页面代码
<form id="form1" enctype="application/x-www-form-urlencoded">
<div>
<input id="txtCode" maxlength="8" name="txtCode" type="text" />
  <img style="cursor: pointer" title="看不清楚,换一张" onclick="this.src='getcode.aspx';" src="getcode.aspx" alt="看不清楚,换一张" align="absMiddle" /><img id="imgRead" style="cursor: pointer" title="收听验证码" onclick="playvoice('player');" src="image/maintb.gif" alt="收听验证码" align="absMiddle" /></div>
</form>

点收听验证码时调用的js函数如下:

function playvoice(id) {
     var voiceid = document.getElementById(id);
     var voicecode = $.cookie('ValidateCode');
     voiceid.innerHTML = "<object id="sound_play" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="0" height="0" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="name" value="sound_play" /><param name="flashvars" value="isPlay=1&amp;url=codevoice.aspx&amp;code=&quot; + voicecode + &quot;" /><param name="src" value="sound_play.swf?&quot; + (new Date().getTime()) + &quot;" /><embed id="sound_play" type="application/x-shockwave-flash" width="0" height="0" src="sound_play.swf?&quot; + (new Date().getTime()) + &quot;" flashvars="isPlay=1&amp;url=codevoice.aspx&amp;code=&quot; + voicecode + &quot;" name="sound_play"></embed></object>";
 }

其中$.cookie('ValidateCode')是读取cookie验证码,这里使用了一个jquery操作cookie插件

生成mp3页面代码如下:
//读取验证码生成mp3,这里包括头部begin.mp3和尾部end.mp3

Response.ContentType = "audio/mpeg";
Response.WriteFile("sound/begin.mp3");
string checkCode = HttpContext.Current.Request.QueryString["code"].ToString();// string checkCode ="8888";
if (checkCode.Length &gt; 0)
for (int i = 0; i &lt; checkCode.Length; i++)
{
Response.WriteFile("sound/"+checkCode[i] + ".mp3");
}
Response.WriteFile("sound/end.mp3");

详细如下:getcode

 

public partial class getcode : System.Web.UI.Page
{
private int letterWidth = 20;//单个字体的宽度范围
private int letterHeight = 20;//单个字体的高度范围
private int letterCount = 8;//验证码位数
private char[] chars = "0123456789".ToCharArray();
private string[] fonts = { "Arial", "Georgia" };
/// <summary>
/// 产生波形滤镜效果
/// </summary>
private const double PI = 3.1415926535897932384626433832795;
private const double PI2 = 6.283185307179586476925286766559;
protected void Page_Load(object sender, EventArgs e)
{
//防止网页后退--禁止缓存
Response.Expires = 0;
Response.Buffer
= true;
Response.ExpiresAbsolute
= DateTime.Now.AddSeconds(-1);
Response.AddHeader(
"pragma", "no-cache");
Response.CacheControl
= "no-cache";
string str_ValidateCode = GetRandomNumberString(letterCount);
HttpCookie objCookie
= new HttpCookie("ValidateCode");
objCookie.Value
= str_ValidateCode;
objCookie.Path
= "/";
objCookie.Expires
= DateTime.Now.AddSeconds(60);
Response.Cookies.Add(objCookie);
CreateImage(str_ValidateCode);

}
public void CreateImage(string checkCode)
{
int int_ImageWidth = checkCode.Length * letterWidth;
Random newRandom
= new Random();
Bitmap image
= new Bitmap(int_ImageWidth, letterHeight);
Graphics g
= Graphics.FromImage(image);
//生成随机生成器
Random random = new Random();
//白色背景
g.Clear(Color.White);
//画图片的背景噪音线
for (int i = 0; i < 10; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);

g.DrawLine(
new Pen(Color.Silver), x1, y1, x2, y2);
}

//画图片的前景噪音点
for (int i = 0; i < 10; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);

image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//随机字体和颜色的验证码字符

int findex;
for (int int_index = 0; int_index < checkCode.Length; int_index++)
{
findex
= newRandom.Next(fonts.Length - 1);
string str_char = checkCode.Substring(int_index, 1);
Brush newBrush
= new SolidBrush(GetRandomColor());
Point thePos
= new Point(int_index * letterWidth + 1 + newRandom.Next(3), 1 + newRandom.Next(3));
g.DrawString(str_char,
new Font(fonts[findex], 12, FontStyle.Bold), newBrush, thePos);
}
//灰色边框
g.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, int_ImageWidth - 1, (letterHeight - 1));
//图片扭曲
//image = TwistImage(image, true, 3, 4);
//将生成的图片发回客户端
MemoryStream ms = new MemoryStream();
image.Save(ms, ImageFormat.Png);
Response.ClearContent();
//需要输出图象信息 要修改HTTP头
Response.ContentType = "image/Png";
Response.BinaryWrite(ms.ToArray());
g.Dispose();
image.Dispose();
}
/// <summary>
/// 正弦曲线Wave扭曲图片
/// </summary>
/// <param name="srcBmp">图片路径</param>
/// <param name="bXDir">如果扭曲则选择为True</param>
/// <param name="nMultValue">波形的幅度倍数,越大扭曲的程度越高,一般为3</param>
/// <param name="dPhase">波形的起始相位,取值区间[0-2*PI)</param>
/// <returns></returns>
public System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
{
System.Drawing.Bitmap destBmp
= new Bitmap(srcBmp.Width, srcBmp.Height);

// 将位图背景填充为白色
System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(destBmp);

graph.FillRectangle(
new SolidBrush(System.Drawing.Color.White), 0, 0, destBmp.Width, destBmp.Height);

graph.Dispose();

double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;

for (int i = 0; i < destBmp.Width; i++)
{
for (int j = 0; j < destBmp.Height; j++)
{
double dx = 0;

dx
= bXDir ? (PI2 * (double)j) / dBaseAxisLen : (PI2 * (double)i) / dBaseAxisLen;

dx
+= dPhase;

double dy = Math.Sin(dx);

// 取得当前点的颜色
int nOldX = 0, nOldY = 0;

nOldX
= bXDir ? i + (int)(dy * dMultValue) : i;

nOldY
= bXDir ? j : j + (int)(dy * dMultValue);

System.Drawing.Color color
= srcBmp.GetPixel(i, j);
if (nOldX >= 0 && nOldX < destBmp.Width && nOldY >= 0 && nOldY < destBmp.Height)
{
destBmp.SetPixel(nOldX, nOldY, color);
}
}
}
return destBmp;
}
public Color GetRandomColor()
{
Random RandomNum_First
= new Random((int)DateTime.Now.Ticks);
System.Threading.Thread.Sleep(RandomNum_First.Next(
50));
Random RandomNum_Sencond
= new Random((int)DateTime.Now.Ticks);
int int_Red = RandomNum_First.Next(210);
int int_Green = RandomNum_Sencond.Next(180);
int int_Blue = (int_Red + int_Green > 300) ? 0 : 400 - int_Red - int_Green;
int_Blue
= (int_Blue > 255) ? 255 : int_Blue;
return Color.FromArgb(int_Red, int_Green, int_Blue);
}
// 生成随机数字字符串
public string GetRandomNumberString(int int_NumberLength)
{
Random random
= new Random();
string validateCode = string.Empty;
for (int i = 0; i < int_NumberLength; i++)
validateCode
+= chars[random.Next(0, chars.Length)].ToString();
return validateCode;
}

}
codevoice:
public partial class codevoice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//读取验证码生成mp3,这里包括头部begin.mp3和尾部end.mp3
Response.ContentType = "audio/mpeg";
Response.WriteFile(
"sound/begin.mp3");
string checkCode = HttpContext.Current.Request.QueryString["code"].ToString();// string checkCode ="8888";
if (checkCode.Length > 0)
for (int i = 0; i < checkCode.Length; i++)
{
Response.WriteFile(
"sound/"+checkCode[i] + ".mp3");
}
Response.WriteFile(
"sound/end.mp3");
}

}

Default前台布局:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Soudcode._Default" %>

<!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>
<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js" type="text/javascript"></script>
<script src="js/jquery.cookie.js" type="text/javascript"></script>
<script type="text/jscript" >
function playvoice(id) {
var voiceid = document.getElementById(id);
var voicecode = $.cookie('ValidateCode');
voiceid.innerHTML
= "<embed id='sound_play' name='sound_play' src='sound_play.swf?" + (new Date().getTime()) + "' FlashVars='isPlay=1&url=codevoice.aspx&code=" + voicecode + "' width='0' height='0' allowScriptAccess='always' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer' /></embed>";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" name="txtCode" id="txtCode" maxlength="8" />
<img onclick="this.src='getcode.aspx';" src="getcode.aspx" align="absmiddle" style="cursor: pointer" alt="看不清楚,换一张" title="看不清楚,换一张" /><img id="imgRead" src="image/maintb.gif" align="absmiddle" style="cursor: pointer" alt="收听验证码" title="收听验证码" onclick="playvoice('player');" /><span id="player"></span>
</div>
</form>
</body>
</html>


posted @ 2011-05-09 10:00  brainmao  阅读(1410)  评论(0编辑  收藏  举报