1.首先生成不重复的字符串,以下是主要代码:
int
rep = 0;
string
str =
string
.Empty;
long
num2 =
DateTime
.Now.Ticks + rep;
rep++;
Random
random =
new
Random
(((
int
)(((
ulong
)num2) & 0xffffffffL)) | ((
int
)(num2 >> rep)));
for
(
int
i = 0; i < 4; i++)
{
char
ch;
int
num = random.Next();
if
((num % 2) == 0)
{
ch = (
char
)(0x30 + ((
ushort
)(num % 10)));
}
else
{
ch = (
char
)(0x41 + ((
ushort
)(num % 0x1a)));
}
str = str + ch.ToString();
}
Code = str;
该算法会生成0,o,1,i等容易混淆的字符,后期我们会稍作调整。
2.生成字符过后,我们需要把字符生成图片。
int
randAngle = 45;
//
随机转动角度
int
mapwidth = (
int
)(Code.Length * 22);
Bitmap
map =
new
Bitmap
(mapwidth, 28);
//
创建图片背景
Graphics
graph =
Graphics
.FromImage(map);
graph.Clear(
Color
.AliceBlue);
//
清除画面,填充背景
Random
rand =
new
Random
();
//
验证码旋转,防止机器识别
char
[] chars = Code.ToCharArray();
//
拆散字符串成单字符数组
//
文字距中
StringFormat
format =
new
StringFormat
(
StringFormatFlags
.NoClip);
format.Alignment =
StringAlignment
.Center;
format.LineAlignment =
StringAlignment
.Center;
再画一条曲线连接所有字符
double
x1 = 10;
double
y1 = 0;
for
(
double
x = 1; x < 720; x++)
{
Pen
pen =
new
Pen
(
Color
.Blue, rand.Next(3));
//SIN
最大值为
1,
而我图上用了
100
像素
,
所以有
//100/1=100
故而
y
要乘
100;
// x/180*Math.PI
这个表达式把角度换成弧度值
double
y =
Math
.Sin(x / 180 *
Math
.PI) * 28;
//SIN
值一个循环为
360
度,而我图上用了
200
像素表示,所以有:
//360/200=1.8
故而
x
值要除
1.8
graph.DrawLine(pen, (
float
)x1, (
float
)y1 + 1, (
float
)(x) + 1, (
float
)y + 1);
x1 = x + 1;
y1 = y;
}
string
[] fontArray = {
"Verdana"
,
"Microsoft Sans Serif"
,
"Comic Sans MS"
,
"Arial"
,
"
宋体
"
};
for
(
int
i = 0; i < chars.Length; i++)
{
Font
fontstyle =
new
Font
(fontArray[rand.Next(5)], rand.Next(20, 22),
FontStyle
.Regular);
//
字体样式
Point
dot =
new
Point
(rand.Next(14, 16), 16);
//graph.DrawString(dot.X.ToString(), fontstyle, new SolidBrush(Color.Black), 10, 150); //
测试
X
坐标显示间距的
float
angle = rand.Next(-randAngle, randAngle);
//
转动的度数
graph.TranslateTransform(dot.X, dot.Y);
//
移动光标到指定位置
graph.RotateTransform(angle);
graph.DrawString(chars[i].ToString(), fontstyle,
new
SolidBrush
(
Color
.Blue), 1, 1, format);
graph.RotateTransform(-angle);
//
转回去
graph.TranslateTransform(2, -dot.Y);
//
移动光标到指定位置
}
//
生成图片
System.IO.
MemoryStream
ms =
new
System.IO.
MemoryStream
();
map.Save(ms, System.Drawing.Imaging.
ImageFormat
.Gif);
CodeMap =
new
Bitmap
(map);
graph.Dispose();
map.Dispose();
详解地址:http://www.517up.com/chat/%E4%BB%8E%E9%AA%8C%E8%AF%81%E7%A0%81%E8%AF%B4%E8%B5%B7?postbadges=true