Asp.Net动态生成验证码实例
最近因为本站的留言本和发表评论不断出现有些人在恶意发表信息,所以做了一个生成验证码生成图片的功能,现拿出来和大家共享(做了几种方法,大家可取自己所要的代码即可)。
首先用VS2005建立一个ImgCheckCode.aspx文件,ImgCheckCode.aspx文件内空只要第一句就OK,下面的可以删除,来看ImgCheckCode.aspx.vb文件的内容:
Imports
System.Drawing
Imports
System.Drawing.Imaging
Imports
System.Drawing.Drawing2D
Partial
Class ImgCheckCode
Class ImgCheckCode
Inherits System.Web.UI.Page
Protected Sub Page_Load()Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'ImgCheck1() '图片验证码1
'draw2(getNum.ToString)'图片验证码2
'GenImg(GenCode(4)) '图片验证码3
CreateCheckCodeImage(GenCode(4)) '图片验证码3(增加背景噪音线、前景噪音点)
End Sub
图片验证码1#Region " 图片验证码1 "
Sub ImgCheck1()Sub ImgCheck1()
'生成随机生成器
Dim random As Random = New Random()
Dim validateNum As String = ""
Dim s As String = "0123456789"
Dim i As Integer
For i = 0 To 4 - 1 Step i + 1
validateNum += s(random.Next(s.Length))
Next
HttpContext.Current.Session("Code") = validateNum
Dim image As Bitmap = New Bitmap(CType(Math.Ceiling(validateNum.Length * 12.5), Integer), 18)
Dim g As Graphics = Graphics.FromImage(image)
Try
'清空图片背景色
g.Clear(Color.White)
Dim font As Font = New Font("Arial", 10, (FontStyle.Bold))
Dim brush As LinearGradientBrush = New LinearGradientBrush(New Rectangle(0, 0, image.Width, image.Height), Color.OrangeRed, Color.OrangeRed, 1.2F, True)
g.DrawString(validateNum, font, brush, random.Next(1) + 1, random.Next(1) + 1)
'画图片的边框线
g.DrawRectangle(New Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1)
'保存图片数据
Dim stream As IO.MemoryStream = New IO.MemoryStream()
image.Save(stream, ImageFormat.Jpeg)
'输出图片
Response.Clear()
Response.ContentType = "image/jpeg"
Response.BinaryWrite(stream.ToArray())
Finally
g.Dispose()
image.Dispose()
End Try
End Sub
#End Region
图片验证码2#Region " 图片验证码2 "
Private Function getNum()Function getNum() As Int64
Dim zNum As Int64
Randomize(Timer)
zNum = CInt(8999 * Rnd() + 1000)
Session("Code") = zNum
Return zNum
End Function
Private Sub draw()Sub draw()
Response.ContentType = "image/jpeg"
Dim width As Int32
Dim height As Int32
width = 300
height = 300
Dim x, y As Int16
x = 30
y = 50
Dim zNum
Randomize(Timer)
zNum = CInt(8999 * Rnd() + 1000)
Session("Code") = zNum
Dim objBitmap As Bitmap
objBitmap = New Bitmap(width, height)
Dim objGraphics As Graphics
objGraphics = Graphics.FromImage(objBitmap)
objGraphics.DrawRectangle(New Pen(Color.Black), 0, 0, width, height)
objGraphics.FillRectangle(New SolidBrush(Color.White), 1, 1, width - 2, height - 2)
Dim objBrush As New SolidBrush(Color.Blue)
objGraphics.SmoothingMode = SmoothingMode.AntiAlias
objBitmap.Save(Response.OutputStream, ImageFormat.Jpeg)
objGraphics.Dispose()
objBitmap.Dispose()
End Sub
Private Sub draw2()Sub draw2(ByVal str As String)
Dim image As New Bitmap(600, 200)
Dim axesfont As New Font("arial", 90, FontStyle.Bold)
Dim blackbrush As New SolidBrush(Color.SteelBlue)
Dim redpen As New Pen(Color.Red, 5)
Dim blackpen As New Pen(Color.Black, 2)
Dim g As Graphics
g = Graphics.FromImage(image)
g.Clear(Color.White)
g.FillRectangle(New SolidBrush(Color.White), 0, 0, 600, 200)
g.DrawString(str, axesfont, blackbrush, 10, 10)
image.Save(Response.OutputStream, ImageFormat.Jpeg)
End Sub
Function NumCode()Function NumCode()
Response.Expires = -1
Response.AddHeader("Pragma", "no-cache")
Response.AddHeader("cache-ctrol", "no-cache")
On Error Resume Next
Dim zNum, i, j
Dim Ados, Ados1
Randomize(Timer)
zNum = CInt(8999 * Rnd() + 1000)
Session("Code") = zNum
Dim zimg(4), NStr
NStr = CStr(zNum)
For i = 0 To 3
zimg(i) = CInt(Mid(NStr, i + 1, 1))
Next
Dim Pos
Ados = Server.CreateObject("Adodb.Stream")
Ados.Mode = 3
Ados.Type = 1
Ados.Open()
Ados1 = Server.CreateObject("Adodb.Stream")
Ados1.Mode = 3
Ados1.Type = 1
Ados1.Open()
Ados.LoadFromFile(Server.MapPath("body.Fix"))
Ados1.write(Ados.read(1280))
For i = 0 To 3
Ados.Position = (9 - zimg(i)) * 320
Ados1.Position = i * 320
Ados1.write(Ados.read(320))
Next
Ados.LoadFromFile(Server.MapPath("head.fix"))
Pos = System.Text.Encoding.Default.GetBytes(Ados.read()).Length()
Ados.Position = Pos
For i = 0 To 9 Step 1
For j = 0 To 3
Ados1.Position = i * 32 + j * 320
Ados.Position = Pos + 30 * j + i * 120
Ados.write(Ados1.read(30))
Next
Next
Response.ContentType = "image/BMP"
Ados.Position = 0
Response.BinaryWrite(Ados.read())
Ados.Close() : Ados = Nothing
Ados1.Close() : Ados1 = Nothing
If Err.Description <> "" Then Session("Code") = 9999
Return Session("Code")
End Function
#End Region
图片验证码3#Region " 图片验证码3 "
'产生随机字符串
Private Function GenCode()Function GenCode(ByVal num As Integer) As String
Dim [source] As String() = {"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", "V", "W", "X", "Y", "Z"}
Dim code As String = ""
Dim rd As Random = New Random()
Dim i As Integer
For i = 0 To num - 1 Step i + 1
code += source(rd.Next(0, source.Length))
Next
Return code
End Function
'生成图片
Private Sub GenImg()Sub GenImg(ByVal code As String)
Dim myPalette As Bitmap = New Bitmap(60, 18) '定义一个画板
Dim gh As Graphics = Graphics.FromImage(myPalette) '在画板上定义绘图的实例
Dim rc As Rectangle = New Rectangle(0, 0, 60, 18) '定义一个矩形
gh.FillRectangle(New SolidBrush(Color.DarkSeaGreen), rc) '填充矩形
gh.DrawString(code, New Font("Arial", 12), New SolidBrush(Color.White), rc) '在矩形内画出字符串
myPalette.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg) '将图片显示出来
Session("Code") = code '将字符串保存到Session中,以便需要时进行验证
gh.Dispose()
myPalette.Dispose()
End Sub
'生成图片(增加背景噪音线、前景噪音点)
Private Sub CreateCheckCodeImage()Sub CreateCheckCodeImage(ByVal checkCode As String)
If checkCode = Nothing Or checkCode.Trim() = String.Empty Then
Return
End If
Session("Code") = checkCode '将字符串保存到Session中,以便需要时进行验证
Dim image As System.Drawing.Bitmap = New System.Drawing.Bitmap(CType(Math.Ceiling((checkCode.Length * 12.5)), Integer), 22)
Dim g As Graphics = Graphics.FromImage(image)
Try
'生成随机生成器
Dim random As Random = New Random()
'清空图片背景色
g.Clear(Color.White)
'画图片的背景噪音线
Dim i As Integer
For i = 0 To 25 - 1 Step i + 1
Dim x1 As Integer = random.Next(image.Width)
Dim x2 As Integer = random.Next(image.Width)
Dim y1 As Integer = random.Next(image.Height)
Dim y2 As Integer = random.Next(image.Height)
g.DrawLine(New Pen(Color.Silver), x1, y1, x2, y2)
Next
Dim font As Font = New System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold))
Dim brush As System.Drawing.Drawing2D.LinearGradientBrush = New System.Drawing.Drawing2D.LinearGradientBrush(New Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2F, True)
g.DrawString(checkCode, font, brush, 2, 2)
'画图片的前景噪音点
Dim j As Integer
For j = 0 To 100 - 1 Step j + 1
Dim x As Integer = random.Next(image.Width)
Dim y As Integer = random.Next(image.Height)
image.SetPixel(x, y, Color.FromArgb(random.Next()))
Next
'画图片的边框线
g.DrawRectangle(New Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1)
Dim ms As System.IO.MemoryStream = New System.IO.MemoryStream()
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif)
Response.ClearContent()
Response.ContentType = "image/Gif"
Response.BinaryWrite(ms.ToArray())
Finally
g.Dispose()
image.Dispose()
End Try
End Sub
#End Region
End Class
这里俺就使用了第三种方法的第一种(
增加背景噪音线、前景噪音点),如你想用前面的几种可以把Page_Load中的后三名屏蔽它就OK咯,然后在你想要放验证码的页面中插入以下代码即可:
<
asp:Image
id
="ImgCode"
runat
="server"
ImageUrl
="ImgCheckCode.aspx"
/>
简单吧,嘻嘻,快试试吧。 (再附上一种C#的方法让大家下载吧,见附件)
<script type="text/javascript">
</script> <script type="text/javascript">
</script>