Image verification code implementation

Source: Internet
Author: User
Purpose:
  
To prevent malicious users from using robots (malicious programs) for automatic registration, automatic logon, malicious bumping, malicious database access, and brute force password cracking using specific programs, the verification code technology can be used.
Another benefit is that it gives your website a cool feeling.
  
   Verification Code Application Principle:
The browser uses the HTML standard to dynamically associate with the website server. in HTML forms, the POST method with the specified action is basically used. If the verification code method is not applied, it is easy for some people with ulterior motives to use robot programs or use malicious programs that steal actions to achieve their personal activities. After the verification code technology is applied, you can protect your server against this problem.
If you are required to read a verification code image generated by the server and enter the verification code when entering the form content. After receiving such a form, the server first compares the Verification Code submitted by the user with the session value (the session value is generated when the verification code image is generated, determine whether the user uses the website functions properly based on the comparison results.
  
   Considerations for verification code application:
In order to prevent the computer OCR program from recognizing and cracking the verification code, it is generally necessary to increase the difficulty of recognizing the verification code picture within a reasonable range. Currently, common methods include mixing numbers and letters, twisting and turning characters, increasing background noise, adding interference stripes, randomly changing the position of characters on the image, and changing the background color. It is difficult for users to recognize verification codes, which affects users' enthusiasm for using the website.
After the verification code is applied to a website, the pressure on the server is increased. One is that the verification code generated will take up the server's CPU time, and the other is that the application session will consume the server's memory. Therefore, it is not used everywhere on the website. Currently, many applications are used in submitting forms.
  
   Verification Code style:
  
The sample programs in this article provide the following patterns and functions:
Standard Style:
Random style of background color:
Random Variation of interference lines:
Random variation pattern of Interference Noise:
Random Variation of distortion degree:
Random Variation of the first character position:
Add a 3D shadow style randomly:
Random Variation of character quantity:
Random font size variation:
  
Yahoo Verification Code style:
  
  
Csdn Verification Code style:
  
  
Sina verification code style:
  
  
Phoenix network verification code style:
  
  
   Verification code generation method:
  
1. randomly generate characters of a certain length;
2. Use the graphics class method of the system. Drawing namespace to draw characters into an image;
3. On the basis of step 2, it also applies the method in step 2 to complicate the image and increase the recognition difficulty. Generally, the second step does not conform to the third step.
  
   Verification Code application foreground program:
  

The following is a code snippet:
<Body>
<Form ID = "form1" runat = "server">
<Div>
<Asp: textbox id = "textbox1" runat = "server"> </ASP: textbox>
<Asp: Image id = "image1" runat = "server" imageurl = "verifychar. aspx"/> <br/>
<Br/>
<Asp: button id = "button1" runat = "server" text = "Submit"/> </div>
</Form>
</Body>

The core of the program is to point the URL referenced by the image to the Verification Code Image Generation Program.
  
  Verification Code Image Generation Program:
The following programs are used in vs2003 and vs2005.
  

The following is a code snippet:
  

Imports system. Io
Imports system. Drawing
Imports system. Drawing. Imaging
Imports system. Drawing. drawing2d

Partial class verifychar
Inherits system. Web. UI. Page

Private const PI as double = 3.14159265358979
Private const pi2. as double = 6.28318530717959

  
Private sub page_load (byval sender as system. Object, byval e as system. eventargs) handles mybase. Load
Response. cache. setcacheability (system. Web. httpcacheability. nocache) 'not cached
Dim X, Y, X1, Y1 as single
Dim penwidth1, penwid2, verifyvharfont as integer
Dim verifychar as string = rndchar (4) 'rndchar is a UDF
Dim IMG as system. Drawing. Bitmap
Dim G as graphics
Dim backbrush as brush = brushes. dimgray
Dim textbrush as brush = brushes. Black
Verifyvharfont = int (7 * RND () + 14' random font size of Verification Code characters
Dim textfont as new font ("Arial", verifyvharfont, fontstyle. Strikeout) 'verification code font
Dim MS as memorystream
Dim gwidth as integer = int (LEN (verifychar) * verifyvharfont + verifyvharfont 'verification area width. If all characters are W, it cannot be widened.
IMG = new Bitmap (gwidth, 30) 'height of the verification area

'Generate random background color
Dim nred, ngreen, nblue as integer, ternary background color
Dim RD = new random '(CINT (system. datetime. Now. ticks ))
Nred = RD. Next (255) mod 128 + 128
Ngreen = RD. Next (255) mod 128 + 128
Nblue = RD. Next (255) mod 128 + 128

'Create a new blank graphics on the piccanvas.
G = graphics. fromimage (IMG)

'Fill the bitmap background
G. fillrectangle (New solidbrush (system. Drawing. color. fromargb (nred, ngreen, nblue), 0, 0, IMG. Width, IMG. Height)

'Random output noise Line'
Dim I as int32
For I = 0 to 2
Randomize ()
X = IMG. Width * RND ()
Y = IMG. Height * RND ()
X1 = IMG. Width * RND ()
Y1 = IMG. Height * RND ()
Penwidth1 = 2 * RND () '. You can modify the parameters to obtain different results.
G. drawline (new pen (backbrush, penwidth1), X, Y, X1, Y1)
Next

'Random output noise
You can modify the parameters of penwid2' to obtain different results.
For I = 0 to 10
Randomize ()
X = IMG. Width * RND ()
Y = IMG. Height * RND ()
Nred = RD. Next (255) mod 128 + 128
Ngreen = RD. Next (255) mod 128 + 128
Nblue = RD. Next (255) mod 128 + 128
G. drawrectangle (new pen (color. fromargb (nred, ngreen, nblue), penwid2), X, Y, 1, 1)
Next

'Text location
X = 16 * RND ()-6' randomly generates the X axis position, increasing the difficulty of program recognition.
Y = 0

'Randomly draw 3D backgrounds
Dim s3d as single = RND ()
If s3d> 0.9 then
For I = 1 to 0 step-1
G. drawstring (verifychar, textfont, backbrush, X-I, Y + I)
Next
End if

'Shift the global transform (x, y), that is, move all the content to be drawn on the canvas to the left X, move y down
G. translatetransform (1.5, 1)

'Do shear, move the bottom edge of the original rectangle horizontally 0.2 times the height of the rectangle
Dim texttransform as matrix = G. Transform
Texttransform. shear (0.2, 0)
G. Transform = texttransform

'Draw text
G. drawstring (verifychar, textfont, textbrush, x, y)
Me. Session ("verifychar") = verifychar write verification characters to the session for foreground calls

'Distort verification characters. The twistimage parameter can be modified by yourself.
Dim twist1, twist2 as single
If s3d> 0.9 then'3d background reduces Distortion
Twist1 = 0
Twist2 = 0
Else
Twist1 = RND () * 3' randomly generated distortion parameters
Twist2 = RND () * 2' randomly generated distortion parameters
End if
IMG = twistimage (IMG, true,-twist1,-twist2)
IMG = twistimage (IMG, false, twist1, twist2) 'It does not matter if it is distorted several times, but it only consumes more server resources.

MS = new memorystream
IMG. Save (MS, imageformat. PNG)
Response. clearcontent () 'needs to output image information to modify the HTTP Header
Response. contenttype = "image/PNG"
Response. binarywrite (Ms. toarray ())
G. Dispose ()
IMG. Dispose ()
Response. End ()

End sub

  
'Function name: rndchar
'Function parameter: vcodenum -- set the number of digits of the returned random string
'Function: generate a random string of a specified length consisting of digits and characters.
Function rndchar (byval vcodenum) as string
Dim vchar as string = "3, 5, 5, 6, 7, 7, 9, A, C, E, F, G, H, K, L, M, N, P, R, t, x, y, z "'defines the characters and frequency of the Verification Code
Dim vcarray () as string = Split (vchar, ",") 'generates an array of strings
Vchar = ""
Dim I as byte
For I = 0 to int (vcodenum * RND () + 1' ensure that at least 2 characters are allowed, and a maximum of vcodenum + 1 character is allowed
Randomize ()
Vchar = vchar & vcarray (INT (25 * RND () 'array is generally read from 0, so here it is 25 * RND
Next
Return vchar
End Function

  
'Function name: twistimage
'Function parameters: dmultvalue-waveform amplitude multiple; start phase of the dphase waveform, value range [0-2 * PI); bxdir-distortion Mode
'Function: sine curve wave distorted image. Functions can be used together to obtain different effects in different ways.
'The Genius function can no longer be used to identify the source. Thanks to the original author!
Public Function twistimage (byval srcbmp as bitmap, byval bxdir as Boolean, byval dmultvalue as double, byval dphase as double) as bitmap
Dim destbmp = new Bitmap (srcbmp. Width, srcbmp. Height)
Dim dbaseaxislen as double = IIF (bxdir, cdbl (destbmp. Height), cdbl (destbmp. width) 'todo: Unsupported feature: conditional (?) Operator.

Dim I as integer
For I = 0 to destbmp. Width-1
Dim J as integer
For J = 0 to destbmp. Height-1
Dim DX as double = 0
DX = IIF (bxdir, Pi2 * cdbl (j)/dbaseaxislen, Pi2 * cdbl (I)/dbaseaxislen) 'todo: Unsupported feature: conditional (?) Operator.
Dx + = dphase
Dim dy as double = math. Sin (dx)

'Get the color of the current vertex
Dim noldx as integer = 0
Dim noldy as integer = 0
Noldx = IIF (bxdir, I + CINT (dy * dmultvalue), I) 'todo: Unsupported feature: conditional (?) Operator.
Noldy = IIF (bxdir, J, J + CINT (dy * dmultvalue) 'todo: Unsupported feature: conditional (?) Operator.

Dim color as system. Drawing. Color = srcbmp. getpixel (I, j)
If noldx> = 0 and noldx <destbmp. Width and noldy> = 0 and noldy <destbmp. Height then
Destbmp. setpixel (noldx, noldy, color)
End if
Next J
Next I

Return destbmp
End Function
End Class

 

Source Linke http://bbs.yibai.com.cn/re_bbs.aspx? Bid = 10878

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.