拷贝过来的图片验证码生成类

本文介绍了一种验证码生成器的优化方案,包括算法优化、图像输出和反识别优化等。通过随机选择字体、颜色及样式来增强验证码的安全性,并通过加入噪点提升抗干扰能力。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

修改说明:

1,对源代码做了部分算法优化;

2,对图像输出做了优化;

3,对图像的反识别做了优化;

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Drawing;

namespace Common
... {
/**////<summary>
///验证码模块
///</summary>

publicclassCreateImage
...{
publicstaticvoidDrawImage()
...{
HttpContext.Current.Response.Clear();
CreateImageimg
=newCreateImage();
HttpContext.Current.Session[
"CheckCode"]=img.RndNum(3);
img.CreateImages(HttpContext.Current.Session[
"CheckCode"].ToString());
HttpContext.Current.Response.End();
}


/**////<summary>
///生成验证图片
///</summary>
///<paramname="checkCode">验证字符</param>

privatevoidCreateImages(stringcheckCode)
...{
intiwidth=(int)(checkCode.Length*13);
System.Drawing.Bitmapimage
=newSystem.Drawing.Bitmap(iwidth,20);
Graphicsg
=Graphics.FromImage(image);
g.Clear(Color.White);
//定义颜色
Color[]c=...{Color.Black,Color.Red,Color.DarkBlue,Color.Green,Color.Orange,Color.Brown,Color.DarkCyan,Color.Purple};
//定义字体
string[]font=...{"Verdana","MicrosoftSansSerif","ComicSansMS","Arial","宋体"};
Randomrand
=newRandom();

//输出不同字体和颜色的验证码字符
for(inti=0;i<checkCode.Length;i++)
...{
intcindex=rand.Next(7);
intfindex=rand.Next(5);
Fontf;
intk=rand.Next(3);
if(k==1)...{f=newSystem.Drawing.Font(font[findex],13,FontStyle.Bold);}
elseif(k==2)...{f=newSystem.Drawing.Font(font[findex],13,FontStyle.Bold|FontStyle.Strikeout);}
else...{f=newSystem.Drawing.Font(font[findex],13,FontStyle.Bold|FontStyle.Italic);};
Brushb
=newSystem.Drawing.SolidBrush(c[cindex]);
g.DrawString(checkCode.Substring(i,
1),f,b,(i*12),rand.Next(2));
}

//画一个边框
g.DrawRectangle(newPen(Color.Black,0),0,0,image.Width-1,image.Height-1);
//随机输出噪点
for(inti=0;i<50;i++)
...{
intx=rand.Next(image.Width);
inty=rand.Next(image.Height);
floatx1,y1;
x1
=0.5F;
y1
=0.5F;
g.DrawRectangle(
newPen(Color.LightGray,0),x,y,x1,y1);
}

//输出到浏览器
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ContentType
="image/Jpeg";
image.Save(HttpContext.Current.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);
g.Dispose();
image.Dispose();
}


/**////<summary>
///生成随机的字母
///</summary>
///<paramname="VcodeNum">生成字母的个数</param>
///<returns>string</returns>

privatestringRndNum(intVcodeNum)
...{
//采用一个简单的算法以保证生成随机数的不同
Randomrand=newRandom();
intmin=(int)Math.Pow(10,VcodeNum);
intmax=(int)(Math.Pow(10,VcodeNum+1)-1);
returnrand.Next(min,max).ToString();
}

}



}

后来发现了一个图片验证码的网站,蛮有意思:http://www.lafdc.com/captcha/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值