春运最高峰来了!明天通过网络将能买到小年夜的车票,本周四就将开售除夕日车票,但不少人被首次在春运期间使用的图片验证码搞得很火大,小编也正在对验证码进行研究,编写了由C#实现验证码程序,分享给大家
近日铁路订票网“12306”又出现多道另类考题,竟要订票者在8个图案中“点击图中所有美男子”、“请点击下图中所有的非智能眼镜”、“请点击下图中所有的博斯普鲁斯海峡”,网友吐槽:比高考题还难,到底是什么样子的,先跟大家分享一下几个例子:

哈哈,是有点奇葩的验证码,怪不得有人会说“妈妈我已经找不到回家”,这让分秒必争的春运网上抢票者瞬间傻眼,九成网友已经被打败……
正巧小编最近也在研究验证码,参考了许多网上案例,整理了一篇文章特分享给大家。
验证码的一般编写思路为:
1.定义验证码字符长度;
2.根据长度随机生成验证码字符串;
3.将验证码字符串转换成图片形式,并在图片中生成随机噪声点和声线(对验证码进行模糊识别处理);
4.显示结果。
///
/// 生成随机验证码
///
/// 验证码长度
///
public string CreateIdentifyingCode(int CodeLen)
{
if (CodeLen < 1)
return String.Empty;
int num;
string checkcode = String.Empty;
Random random = new Random();
for (int index = 0; index < CodeLen; index++)
{
num = random.Next();
if (num % 2 == 0)
checkcode += (char)('0' + (char)(num % 10));
else
checkcode += (char)('A' + (char)(num % 26));
}
return checkcode;
}
-------------------------------------------------------------------------------------------------
///
/// 生成验证码图片
///
///
///
private void CreateCheckCodeImage(string checkcode)
{
if (checkcode == null || checkcode.Trim() == String.Empty)
return;
//创建图片大小
System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling(checkcode.Length*12.5),22);
//创建画板
Graphics graphic = Graphics.FromImage(image);
try
{
Random random = new Random();
graphic.Clear(Color.White);
int x1 = 0, y1 = 0, x2 = 0, y2 = 0;
//画图片背景噪声线
for (int index = 0; index < 25; index++)
{
x1 = random.Next(image.Width);
y1 = random.Next(image.Height);
x2 = random.Next(image.Width);
y2 = random.Next(image.Height);
graphic.DrawLine(new Pen(Color.Silver),x1,y1,x2,y2);
}
Font font = new System.Drawing.Font("Helvetica", 12, (FontStyle.Bold |FontStyle.Italic));
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),Color.Blue,Color.DarkBlue,1.2f,true);
graphic.DrawString(checkcode,font,brush,2,2);
int x = 0;
int y = 0;
// 画图片的前景噪声点
for (int index = 0; index < 100; index++)
{
x = random.Next(image.Width);
y = random.Next(image.Height);
image.SetPixel(x,y,Color.FromArgb(random.Next()));
}
//画图片的边框线
graphic.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
//网页响应
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
finally
{
graphic.Dispose();
image.Dispose();
}
}










