Python image captcha code sharing

  • 2020-04-02 09:40:42
  • OfStack

 
#coding: utf-8 
import Image,ImageDraw,ImageFont,os,string,random,ImageFilter 
def initChars(): 
""" 
 The allowed character set, the initial set of Numbers, case letters  
usage: initChars() 
param: None 
return: list 
 Returns the allowed character set and  
for: picChecker Class initial set of characters  
todo: Nothing 
""" 
nums = [str(i) for i in range(10)] 
letterCase = [ 
'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' 
] 
upperCase = [ 
'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', 
] 
return(nums+letterCase+upperCase) 
class picChecker(): 
""" 

Image verification code:
1) the user needs to fill in the picture verification code to prevent the robot from registering
2) the number of characters of image verification code is 4 bits (case-insensitive letters and Numbers).
If the user does not fill in the verification code or does not fill in the correct verification code,
Page friendly prompt for user to fill in (also limited by the program)
Usage: PC = picChecker (.) createChecker ()
Param: a lot, as follows
Chars allows the set of characters,
Type a list
The default value initChars ()
Example [' 1 ', '2', '3']
Length string length
Type integer
The default value of 4
Size picture size
Type tutle
The default value (120-30)
Example (120-30)
Fontsize fontsize
Type integer
The default value is 25
The begin character is in its position, the upper-left corner
Type tutle
The default value (5, 2)
OutputType outputType
Type a string
The default value of GIF
Optional value GIF JPEG TIFF PNG
Mode picture mode
Type a string
Optional value RGB L (there are other modes, but only these 2 are recommended)
The default value of RGB
BackgroundColor background color
ForegroundColor the foreground
When mode = RGB, backgroundColor, foregroundColor tutle type
Values for (integer, integer, integer)
Represents the RGB color value
When mode = L, backgroundColor foregroundColor for Numbers, said black and white pattern
Values of 0-255
Gray said
Fonttype font path
Type a string
The default value "simsum. TTC"
JamNum interferes with the number of lines
Type (int1, int1)
Int1 interference line number lower limit, including
Int2 interference line number line, including
PointBorder scatter noise
Construction: use a random function for each pixel to determine whether to draw scattered noise on that pixel
Type (int1, int2)
The larger the int1, the more scattered it is
The larger the int2, the fewer scatter points
Return: [picCheckerStr, PIC]
PicCheckerStr: returns the corresponding string in the image and can be used for session validation and other purposes
PIC: the Image returned, of type Image
For:
Todo: Nothing
"" "
Default font path
# DEFAULT_FONT_PATH = OS. Path. Join (OS) path) dirname (__file__), 'simsun. TTC). Replace (' \ \', '/')
Def arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration arbitration
Begin = (5,-2),outputType = 'GIF',mode = 'RGB',
BackgroundColor = (255,255,255), foregroundColor = (0,0,255),
Fonttype = "simsun.ttc",length = 4,jamNum = (1,2),
PointBorder = (40 33) 6) :
"" "
Initialization configuration
"" "
# captcha configuration
# allowed string
Self. Chars = chars
# picture size
Self. Size = the size
The # character begins at the insertion point
The self. The begin = the begin
# string length
The self. The length = length
# output type
Self. OutputType = outputType
# character size
Self. Fontsize = fontsize
# picture mode
The self mode = mode
# the background color
The self. The backgroundColor = backgroundColor
# the foreground
Self. ForegroundColor = foregroundColor
Number of lines
Self. JamNum = jamNum
Scatter noise limit
Self. PointBorder = pointBorder
# font library path
Self. Fonttype = fonttype
Set the font size to 18 by default
The self. The font = ImageFont. Truetype (self. Fonttype, self. Fontsize)
Def getPicString (self) :
"" "
Usage: getPicString ()
Return: string
For: generates a random string of a given length
Todo: Nothing
"" "
# initializes the string length
Length = self. Length
# initializes the set of characters
Chars = self. Chars
# gets the set of characters
SelectedChars = the random sample (chars, length)
CharsToStr = string. Join (selectedChars, ' ')
Return (charsToStr)
Def createChecker (self) :
"" "
Usage: createChecker ()
Return: [STR, PIC]
STR: the corresponding string
PIC: the corresponding picture
For:
Todo:
"" "
Get the captcha string
RandStr = self. GetPicString ()
Add a string to a space
RandStr1 = string.join([I +" "for I in randStr],"")
# create graphics
Im = Image. The new (self) mode, the self. The size, the self. The backgroundColor)
# create a brush
The draw = ImageDraw. The draw (im)
Output random text
The draw. The text (self. The begin, randStr1, the font = self. The font, the fill = self. ForegroundColor)
# im = self. DrawText (the draw, randStr, im)
Line # interference
Self. CreateJam (draw)
Scattered noise
Self. CreatePoints (draw)
Figure distortion
Para = [1 - float (random randint (1, 2)) / 100,
0,
0,
0,
1 - float (random randint (1, 10)) / 100,
Float (random randint (1, 2)) / 500,
0.001,
Float (random randint (1, 2)) / 500
]
# print randStr, para
Im = im. The transform (im. The size, the Image PERSPECTIVE, para)
Image filter
Im = im. Filter (ImageFilter. EDGE_ENHANCE_MORE)
Im. Save (" the checker. JPG ", the self. OutputType)
Return ([randStr, im])
Def createJam (self, the draw) :
"" "
Usage: create an interference line
Para: draw
Return: None
For:
Todo:
"" "
Number of lines
LineNum = random. Randint (self. JamNum [0], the self. The jamNum [1])
For I in range (lineNum) :
The begin = (random randint (0, the self. The size of [0]), the random. Randint (0, the self. The size [1]))
End = (random randint (0, the self. The size of [0]), random. The randint (0, the self. The size of [1]))
The draw. The line ([begin and end], the fill = (0, 0))
Def createPoints (self, the draw) :
"" "
Usage: create scatter noise
Para: draw
Return: None
For:
Todo:
"" "
Scattered noise
For the x in the range (self. Size [0]) :
For y in range (self. Size [1]) :
Flag = random. Randint (0, self pointBorder [0])
The if flag > Self. PointBorder [1] :
The draw point ((x, y), the fill = (0, 0))
Del flag
If __name__ = = "__main__" :
C = picChecker ()
T = Arthur c. reateChecker ()
Print (t)

Related articles: