{image}
aspNet的验证码代码怎么写啊
主要代码如下:
//
生成随散轮郑机数字字符串
public
string
GetRandomNumberString(int
int_NumberLength)
{
string
str_Number
=
;
Random
theRandomNumber
=
new
Random();
for
(int
int_index
=
0;
int_index
<
int_NumberLength;
int_index++)
str_Number
+=
(10).ToString();
return
str_Number;
}
生成随机颜色
public
Color
GetRandomColor()
{
Random
RandomNum_First
=
new
Random((int));
//
对于C#的随机数,没什么好桐穗说的
(RandomNum_(50));
Random
RandomNum_Sencond
=
new
Random((int));
//
为了在白色背景上显示 ,尽量生成深色
int
int_Red
=
RandomNum_(256);
int
int_Green
=
RandomNum_(256);
int
int_Blue
=
(int_Red
+
int_Green
400)
?
0
:
400
-
int_Red
-
int_Green;
int_Blue
=
(int_Blue255)
?
255
:
int_Blue;
return
(int_Red,
int_Green,
int_Blue);
}
根据验证字符串生成最终图象
public
void
CreateImage(string
str_ValidateCode)
{
int
int_ImageWidth
=
str_
13;
Random
newRandom
=
new
Random();
//
图高20px
Bitmap
theBitmap
=
new
Bitmap(int_ImageWidth,
20);
Graphics
theGraphics
=
(theBitmap);
//
白色背景
();
//
灰色边框
ngle(new
Pen(,
1),
0,
0,
int_ImageWidth
-
1,
19);
//
10pt的字体
Font
theFont
=
new
Font("Arial",
10);
for
(int
int_index
=
0;
int_index
<
str_;
int_index++)
{
string
str_char
=
str_(int_index,
1);
Brush
newBrush
=
new
SolidBrush(GetRandomColor());
Point
thePos
=
new
Point(int_index
13
+
1
+
(3),
1
+
(3));
g(str_char,
theFont,
newBrush,
thePos);
}
//
将生成的图片发回客户冲颂端
MemoryStream
ms
=
new
MemoryStream();
(ms,
);
ent();
//需要输出图象信息
要修改HTTP头
pe
=
"image/Png";
te(());
();
();
();
}
最后在Page_Load中调用以上代码
private
void
Page_Load(object
sender,
e)
{
if(!IsPostBack)
{
//
4位数字的验证码
string
str_ValidateCode
=
GetRandomNumberString(4);
//
用于验证的Session
Session["ValidateCode"]
=
str_ValidateCode;
CreateImage(str_ValidateCode);
}
}
使用的时候在页面中加入一个Image,将图片路径改为的相对路径即可
src=""
/>在需要验证的地方填入如下代码:
if
(
==
Session["ValidateCode"].ToString())
{
=
"正确!";
}
else
=
"错误!";OK,基本搞定 ,总结一下: