图片扭曲验证码示例
1、首先添加一个Default.aspx文件,放置文本框控件、图片按钮控件与按钮
<asp:TextBox ID="txtCode" runat="server" Width="82px">
</asp:TextBox>
<img id="imgVerify" src="code.aspx" alt="看不清?点击更换" onclick=" this.src = this.src + '?'; " />
<asp:Button ID="Button1" runat="server" Text="确定" onclick="Button1_Click" />
2、给按钮button1添加一个方法
protected void Button1_Click(object sender, EventArgs e)
{
string code = Request.Cookies["CheckCode"].Value;
code = HttpUtility.UrlDecode(code, Encoding.GetEncoding("gb2312"));
if (code == txtCode.Text.Trim())
{
ClientScript.RegisterClientScriptBlock(GetType(), "", "alert('正确!');", true);
}
else
{
ClientScript.RegisterClientScriptBlock(GetType(), "", "alert('错误!');", true);
}
}
3、添加一个code.aspx文件,在code.aspx.cs中实现图片扭曲验证码方法
public partial class Code : Page
{
private const double PI = 5.1415926535897932384626433832795;
private const double PI2 = 5.283185307179586476925286766559;
protected void Page_Load(object sender, EventArgs e)
{
CreateCheckCodeImage(GenerateCheckCode(5));
}
private object[] CreateCode(int strLength)
{
//定义一个字符串数组储存汉字编码的组成元素
var r = new string[16]
{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
var random = new Random();
var bytes = new object[strLength];
/*每循环一次产生一个含两个元素的十六进制字节数组,并将其放入bject数组中
每个汉字有四个区位码组成
区位码第1位和区位码第2位作为字节数组第一个元素
区位码第3位和区位码第4位作为字节数组第二个元素
*/
for (int i = 0; i < strLength; i++)
{
//区位码第1位
int r1 = random.Next(11, 14);
string strR1 = r[r1].Trim();
//区位码第2位
//更换随机数发生器的种子避免产生重复值
random = new Random(r1*unchecked((int) DateTime.Now.Ticks) + i);
int r2;
if (r1 == 13)
{
r2 = random.Next(0, 7);
}
else
{
r2 = random.Next(0, 16);
}
string strR2 = r[r2].Trim();
//区位码第3位
random = new Random(r2*unchecked((int) DateTime.Now.Ticks) + i);
int r3 = random.Next(10, 16);
string strR3 = r[r3].Trim();
//区位码第4位
random = new Random(r3*unchecked((int) DateTime.Now.Ticks) + i);
int r4;
if (r3 == 10)
{
r4 = random.Next(1, 16);
}
else if (r3 == 15)
{
r4 = random.Next(0, 15);
}
else
{
r4 = random.Next(0, 16);
}
string strR4 = r[r4].Trim();
//定义两个字节变量存储产生的随机汉字区位码
byte byte1 = Convert.ToByte(strR1 + strR2, 16);
byte byte2 = Convert.ToByte(strR3 + strR4, 16);
//将两个字节变量存储在字节数组中
var strR = new[] {byte1, byte2};
//将产生的一个汉字的字节数组放入object数组中
bytes.SetValue(strR, i);
}
return bytes;
}
private string GenerateCheckCode(int number)
{
Encoding encoding = Encoding.GetEncoding("gb2312");
object[] bytes = CreateCode(number);
//根据汉字编码的字节数组解码出中文汉字
string str1 = encoding.GetString((byte[]) Convert.ChangeType(bytes[0], typeof (byte[])));
string str2 = encoding.GetString((byte[]) Convert.ChangeType(bytes[1], typeof (byte[])));
string str3 = encoding.GetString((byte[]) Convert.ChangeType(bytes[2], typeof (byte[])));
string str4 = encoding.GetString((byte[]) Convert.ChangeType(bytes[3], typeof (byte[])));
string text = str1 + str2 + str3 + str4;
Response.Cookies.Add(new HttpCookie("CheckCode", text));
return text;
}
private Bitmap TwistImg(Bitmap img, bool isTwist, double nMult, double start)
{
var bitmap = new Bitmap(img.Width, img.Height);
Graphics g = Graphics.FromImage(bitmap);
g.FillRectangle(new SolidBrush(Color.White), 0, 0, bitmap.Width, bitmap.Height);
g.Dispose();
double axisLen = isTwist ? bitmap.Height : bitmap.Width;
for (int i = 0; i < bitmap.Width; i++)
{
for (int j = 0; j < bitmap.Height; j++)
{
double dx = 0;
dx = isTwist ? (PI2*j)/axisLen : (PI2*i)/axisLen;
dx += start;
double dy = Math.Sin(dx);
int ox = 0;
int oy = 0;
ox = isTwist ? i + (int) (dy*nMult) : i;
oy = isTwist ? j : j + (int) (dy*nMult);
Color color = img.GetPixel(i, j);
if (ox >= 0 && ox < bitmap.Width && oy >= 0 && oy < bitmap.Height)
{
bitmap.SetPixel(ox, oy, color);
}
}
}
return bitmap;
}
private void CreateCheckCodeImage(string checkCode)
{
if (checkCode == null || checkCode.Trim() == String.Empty)
{
return;
}
var bitmap = new Bitmap(checkCode.Length + 150, 40);
Graphics g = Graphics.FromImage(bitmap);
try
{
var random = new Random();
g.Clear(Color.White);
var font = new Font("Arial", 24, FontStyle.Bold);
var brush = new LinearGradientBrush(new Rectangle(0, 0, bitmap.Width, bitmap.Height),
Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(checkCode, font, brush, 2, 2);
//画图片的前景噪音点
for (int i = 0; i < 100; i++)
{
int x = random.Next(bitmap.Width);
int y = random.Next(bitmap.Height);
bitmap.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Silver), 0, 0, bitmap.Width - 1, bitmap.Height - 1);
Bitmap bt = TwistImg(bitmap, true, 10, 0);
var memoryStream = new MemoryStream();
bt.Save(memoryStream, ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(memoryStream.ToArray());
}
finally
{
g.Dispose();
bitmap.Dispose();
}
}
}