做登陆页面的随机验证码

来源:互联网 发布:vue.js 图片点击放大 编辑:程序博客网 时间:2024/05/19 19:34

先放上这页代码:(radamdata.aspx是用来产生验证码图片用的)

Imports System.Drawing
Imports System.IO
Partial Class test2
    Inherits System.Web.UI.Page
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ' 在此处放置用户代码以初始化页面
        If Not Page.IsPostBack Then
            Me.GenImg(Me.GenCode(4))
 
        End If
    End Sub
 
    Private 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 New Random()
        Dim i As Integer
        For i = 0 To num - 1
            code += [source](rd.Next(0, [source].Length))
        Next i
        Return code
    End Function 'GenCode
 
 
    '生成图片
    Private Sub GenImg(ByVal code As String)
        Dim myPalette As New Bitmap(60, 20) '定义一个画板
        Dim gh As Graphics = Graphics.FromImage(myPalette) '在画板上定义绘图的实例
        Dim rc As New Rectangle(0, 0, 60, 20) '定义一个矩形
        gh.FillRectangle(New SolidBrush(Color.Silver), rc) '填充矩形
        gh.DrawString(code, New Font("宋体", 16), New SolidBrush(Color.Gray), rc) '在矩形内绘制字串(字串,字体,画笔颜色,左上x.左上y)
        myPalette.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg) '将图片显示出来
        '下面这些也是将图片显示出来的!
        'Dim ms As MemoryStream = New MemoryStream
        'myPalette.Save(ms, Imaging.ImageFormat.Jpeg)
        ' Response.ClearContent()
        ' Response.ContentType = "image/jpeg"
        ' Response.BinaryWrite(ms.ToArray)
        Session("ValidateCode") = code '将字符串保存到Session中,以便需要时进行验证
        gh.Dispose()
        myPalette.Dispose()
    End Sub 'GenImg
 
 
End Class

 ..................................................................................................................................................................

放上调用radamdata.aspx的radamindex.aspx的代码

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 
    End Sub
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        If TextBox1.Text = Session("ValidateCode") Then
            Label1.Text = "haha,你成功了!!!"
        Else
            Label1.Text = "不对哦"
        End If
    End Sub
End Class
然后在randamindex.aspx上放一个image控件,使他的图片连接为randamdata.aspx就行了!!!
原创粉丝点击