重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
建一个YanzhenCard.aspx文件
成都创新互联公司是一家以网站建设公司、网页设计、品牌设计、软件运维、成都网站推广、小程序App开发等移动开发为一体互联网公司。已累计为成都发电机租赁等众行业中小客户提供优质的互联网建站和软件开发服务。
保留%@ Page Language="VB" AutoEventWireup="false" CodeFile="YanzhenCard.aspx.vb" Inherits="YanzhenCard" %,其余删除
如下是代码:
Imports System.IO
Imports System.Drawing
Partial Class YanzhenCard
Inherits System.Web.UI.Page
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Dim VNum As String = GenerateRandom(4)
Session("VNum") = VNum
ValidateCode(VNum)
End If
End Sub
Private Sub ValidateCode(ByVal VNum As String)
Dim Gheight As Integer = CType((VNum.Length * 15), Integer)
Dim Img As Bitmap = New Bitmap(Gheight, 20) 'Bitmap是用于处理由像素数据定义的图像
Dim g As Graphics = Graphics.FromImage(Img) 'Graphics.FromImage 从指定的Image创建新的Graphics
g.DrawString(VNum, New Font("Arial", 12), New SolidBrush(Color.Red), 5, 0) 'g.DrawString()在指定位置并且用指定的Brush和Font对象绘制指定的文本字符串。
Dim ms As MemoryStream = New MemoryStream '创建其支持存储区为内存的流。
Img.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
Response.ClearContent()
Response.ContentType = "image/PNG"
Response.BinaryWrite(ms.ToArray)
Response.Write(VNum)
g.Dispose()
Img.Dispose()
Response.End()
End Sub
Private Shared constant As Char() = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}
Public Shared Function GenerateRandom(ByVal Length As Integer) As String
Dim newRandom As System.Text.StringBuilder = New System.Text.StringBuilder(26)
Dim rd As Random = New Random
Dim i As Integer = 0
While i Length
newRandom.Append(constant(rd.Next(26)))
System.Math.Min(System.Threading.Interlocked.Increment(i), i - 1)
End While
Return newRandom.ToString
End Function
End Class
调用方法:asp:ImageButton ID="Yanzhengma_Card" runat="server" ImageUrl="YanzhenCard.aspx" Height="20px" Width="75px" BorderColor="#6699cc" BorderStyle="Solid" BorderWidth="1px" /
我会C#.net的,不过逻辑应该一样,给你看下吧第一步: 创建生成随机字符的方法private string CreateValidate(int count)
{
//定义验证码中所有的字符
string allchar = "1,2,3,4,5,6,7,8,9,0,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z";
//将验证码中所有的字符保存在一个字符串数组中
string[] allchararray = allchar.Split(',');
//初始化一个随机数
string randomcode = "";
int temp = -1;
//生成一个随机对象
Random rand = new Random();
//根据验证码的位数循环
for (int i = 0; i count; i++)
{
//主要是防止生成相同的验证码
if (temp != -1)
{
//加入时间的刻度
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(35);
if (temp == t)
{
//相等的话重新生成
return CreateValidate(count);
}
temp = t;
randomcode += allchararray[t];
}
//在Session中保存随机验证码
Session["Valid"] = randomcode;
//返回生成的随机字符
return randomcode;
}第二步:创建生成图片的方法:private void CreateImageM(string validateCode)
{
//图像的宽度-与验证码的长度成一定比例
int iwidth = (int)(validateCode.Length * 11.5);
//创建一个长20,宽iwidth的图像对象
System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20);
//创建一个新绘图对象
Graphics g = Graphics.FromImage(image);
//绘图用的字体和字号
Font f = new System.Drawing.Font("Arial", 10, System.Drawing.FontStyle.Bold);
//绘图用的刷子大小
Brush b = new System.Drawing.SolidBrush(Color.White);
//清除背景色,并以深橄榄绿的颜色填充
g.Clear(Color.DarkOliveGreen);
//格式化刷子属性-用指定的刷子、颜色等在指定的范围内画图
g.DrawString(validateCode, f, b, 3, 3);
//创建铅笔对象
Pen blackPen = new Pen(Color.Black, 0);
//创建随机对象
Random rand = new Random();
//随机画线
for (int i = 0; i 5; i++)
{
int y = rand.Next(image.Height);
g.DrawLine(blackPen, 0, y, image.Width, y);
}
//输出绘图
System.IO.MemoryStream ms = new System.IO.MemoryStream();
//将图像保存到指定的流
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
Response.ClearContent();
//配置输出类型
Response.ContentType = "image/Jpeg";
//输出内容
Response.BinaryWrite(ms.ToArray());
//清空不需要的资源
g.Dispose();
image.Dispose();
}第三步:在page_Load事件中调用CreateImageM(CreateValidate(4));第四步:判断服务器端的验证码是否与用户输入的相同protected void Button1_Click(object sender, EventArgs e)
{
//判断服务器端的验证码是否与用户输入的相同
if (TextBox1.Text == Session["Valid"].ToString())
{
//相同则提示欢迎信息
Response.Write("script language='javascript'alert('欢迎光临')/script");
}
else
{
//不相同则提示错误信息
Response.Write("script language='javascript'alert('对不起,验证码错误')/script");
}
}
实现过程,在需要调用的页面使用image控件调用验证码生成的页面,验证码生成的页面生成验证图片且将验证信息保存至Session中,调用页面中通过Session判断用户是否输入正确。道理是这样,以下看代码:
生成验证码页面:
gif.ASPx
%@importnamespace="System"%
%@importnamespace="System.io"%
%@importnamespace="System.Drawing"%
%@importnamespace="System.Drawing.Imaging"%
scriptlanguage="VB"runat="server"
SubPage_Load(ByValSenderAsObject,ByValeAsEventArgs)
'RndNum为生成随机码的函数,
DimVNumAsString=RndNum(4)'该值为生成验证码的位数
Session("VNum")=VNum'读取Session
ValidateCode(VNum) '根据Session生成图片
EndSub
'--------------------------------------------
'生成图象验证码函数
SubValidateCode(ByValVNum)
DimImgAsSystem.Drawing.Bitmap
DimgAsGraphics
DimmsAsMemoryStream
DimgheightAsInteger=Int(Len(VNum)*14)
'gheight为图片宽度,根据字符长度自动更改图片宽度
Img=NewBitmap(gheight,24)
g=Graphics.FromImage(Img)
g.DrawString(VNum,(NewFont("Arial",12)),(NewSolidBrush(Color.Red)),3,3)'在矩形内绘制字串(字串,字体,画笔颜色,左上x.左上y)
ms=NewMemoryStream()
Img.Save(ms,ImageFormat.Png)
Response.ClearContent()'需要输出图象信息要修改HTTP头
Response.ContentType="image/Png"
Response.BinaryWrite(ms.ToArray())
g.Dispose()
Img.Dispose()
Response.End()
EndSub
'--------------------------------------------
'函数名称:RndNum
'函数参数:VCodeNum--设定返回随机字符串的位数
'函数功能:产生数字和字符混合的随机字符串
FunctionRndNum(ByValVcodeNum)
DimVcharAsString="0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z"'需要使用中文验证,可以修改这里和ValidateCode函数中的字体
DimVcArray()AsString=Split(Vchar,",")'将字符串生成数组
DimVNumAsString=""
DimiAsByte
Fori=1ToVcodeNum
Randomize()
VNum=VNumVcArray(Int(35*Rnd()))'数组一般从0开始读取,所以这里为35*Rnd
Next
ReturnVNum
EndFunction
/script
调用页面:
demo.ASPx
scriptlanguage="VB"Runat="Server"
SubPage_Load(Senderasobject,easeventargs)
dimVNumasstring=Session("VNum")
Session.Abandon()
ViewState("VNum")=VNum
EndSub
'下面的事件代码是用来测试验证码
SubbtnSubmit_click(senderasobject,easeventargs)
'判断输入的验证码与所给是否相同
IftxtValidateCode.Text=CStr(ViewState("VNum"))Then
ensonShow.text="fontcolor='red'提示:验证通过/font"
Else
ensonShow.text="所填写的验证码与所给的不符"
EndIf
EndSub
/script
html
body
formrunat="server"
divalign="center"
tablewidth="750"
tr
tdvalign="middle"验证码:/td
!--调用验证图片生成页---
tdvalign="top"asp:Imageid="Image1"runat="server"ImageUrl="gif.aspx"//td
/tr
tr
tdvalign="top"输入验证码:/td
tdvalign="top"asp:textboxID="txtValidateCode"runat="server"TextMode="SingleLine"/fontcolor="#FF0000"size="2"*区分大小写/font/td
/tr
tr
tdcolspan="2"valign="top"align="center"asp:buttonID="btnSubmit"runat="server"Text="验证"onclick="btnSubmit_click"/
asp:labelID="ensonShow"runat="server"/
/td
/tr
/table
/div
/form
/body
/html
新建工程,添加一个picturebox,一个textbox,两个command button
Dim vCode As String
Private Sub Command1_Click()
drawvc
End Sub
Private Sub drawvc() '显示校验码
Dim i, vc, px, py As Long
Dim r, g, b As Byte
Randomize '初始化随机种子
'生成随机校验码
vc = CLng(8999 * Rnd + 1000)
vCode = vc
'显示校验码
Picture1.Cls
Picture1.Print vc
'添加噪点(防止自动图像识别)
For i = 0 To 2000 '画2000个噪点
'画点随机位置
px = CLng(Picture1.Width * Rnd)
py = CLng(Picture1.Height * Rnd)
'画点随机颜色
r = CByte(255 * Rnd)
g = CByte(255 * Rnd)
b = CByte(255 * Rnd)
Picture1.Line (px, py)-(px + 1, py + 1), RGB(r, g, b)
Next
End Sub
Private Sub Command2_Click()
If Text1.Text = vCode Then
MsgBox ("正确")
Else
MsgBox ("错误")
drawvc
End If
End Sub
Private Sub Form_Load()
Picture1.FontSize = 12
Picture1.FontBold = True
Picture1.AutoRedraw = True
drawvc
End Sub
你也可以自己画点其他的东西,增加识别难度