Copy Code code as follows:
#coding: Utf-8
Import Image,imagedraw,imagefont,os,string,random,imagefilter
Def initchars ():
"""
Allowed sets of characters, initial collection numbers, uppercase and lowercase letters
Usage:initchars ()
Param:none
Return:list
Returns the allowed character set and
For:picchecker class initial character set combination
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 ():
"""
Picture Validation Code:
1 user registration needs to fill in the Picture verification code to prevent the robot registration
2 Picture Verification Code character number is 4 digits (uppercase and lowercase letters and numbers, case-insensitive).
If the user does not complete the verification code or does not fill in the correct verification code,
Page friendliness prompts the user to fill in (at the same time the program also make corresponding restrictions)
USAGE:PC = Picchecker (). Createchecker ()
Param: Many, as follows
Chars allows the character set to be combined,
Type list
Default Value Initchars ()
example [' 1 ', ' 2 ', ' 3 ']
Length string Lengths
Type integer
Default Value 4
Size picture Sizes
Type Tutle
Default value (120,30)
Example (120,30)
FontSize Font Size
Type integer
Default Value 25
The begin character is actually positioned, that is, the upper left corner
Type Tutle
Default value (5,-2)
OutputType Output Type
Type string
Default Value GIF
Optional value GIF JPEG TIFF PNG
Mode picture pattern
Type string
Optional value RGB L (there are other modes, but only recommend these 2 kinds)
Default Value RGB
BackgroundColor background Color
Foregroundcolor foreground color
When Mode=rgb, Backgroundcolor,foregroundcolor is tutle type
Value is (Integer,integer,integer)
Represents an RGB color value
When Mode=l, Backgroundcolor,foregroundcolor is a number representing black and white mode
Value is 0-255
Represents grayscale
Fonttype Font Path
Type string
Default value "SIMSUM.TTC"
Number of Jamnum interference lines
Type (INT1,INT1)
Int1 the lower limit of the number of interference lines, including
Int2 Interference line number online, including
Pointborder, scatter noise.
Construct method: Use a random function on each pixel to determine whether to draw a scatter noise on that pixel
Type (INT1,INT2)
The bigger the int1, the more the scatter.
The bigger the Int2, the less the scatter.
return: [Piccheckerstr,pic]
PICCHECKERSTR: Returns the corresponding string in the picture, which can be used for session validation and other purposes
Pic: returned picture, type is image
For:
Todo:nothing
"""
#默认字体路径
#DEFAULT_FONT_PATH = Os.path.join (Os.path.dirname (__file__), ' SIMSUN.TTC '). replace (' \ \ ', '/')
def __init__ (self,chars = Initchars (), size = (120,30), FontSize = 25,
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,39)):
"""
Initialize configuration
"""
#验证码配置
#允许的字符串
Self.chars = chars
#图片大小
Self.size = Size
#字符起始插入点
Self.begin = Begin
#字符串长度
Self.length = length
#输出类型
Self.outputtype = OutputType
#字符大小
Self.fontsize = FontSize
#图片模式
Self.mode = mode
#背景色
Self.backgroundcolor = BackgroundColor
#前景色
Self.foregroundcolor = Foregroundcolor
#干扰线条数
Self.jamnum = Jamnum
#散点噪音界限
Self.pointborder = Pointborder
#字体库路径
Self.fonttype = Fonttype
#设置字体, size defaults to 18
Self.font = Imagefont.truetype (Self.fonttype, Self.fontsize)
def getpicstring (self):
"""
Usage:getpicstring ()
Return:string
For: Generating random strings of a given length
Todo:nothing
"""
#初始化字符串长度
Length = Self.length
#初始化字符集合
chars = Self.chars
#获得字符集合
Selectedchars = Random.sample (chars,length)
Charstostr = String.Join (Selectedchars, ")
Return (CHARSTOSTR)
def createchecker (self):
"""
Usage:createchecker ()
return: [Str,pic]
STR: the corresponding string
Pic: corresponding picture
For
Todo:
"""
#获得验证码字符串
Randstr = self.getpicstring ()
#将字符串加入空格
RANDSTR1 = String.Join ([i+ "" For I in Randstr], "")
#创建图形
im = Image.new (self.mode,self.size,self.backgroundcolor)
#创建画笔
Draw = Imagedraw.draw (IM)
#输出随机文本
Draw.text (Self.begin, RANDSTR1, Font=self.font,fill=self.foregroundcolor)
#im = Self.drawtext (Draw,randstr,im)
#干扰线
Self.createjam (Draw)
#散点噪音
Self.createpoints (Draw)
#图形扭曲
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.transform (im.size, Image.perspective,para)
#图像滤镜
Im=im.filter (Imagefilter.edge_enhance_more)
Im.save ("Checker.jpg", Self.outputtype)
return ([Randstr,im])
def createjam (Self,draw):
"""
Usage: Creating a jamming line
Para:draw represents a brush
Return:none
For
Todo:
"""
#干扰线条数
LineNum = Random.randint (self.jamnum[0],self.jamnum[1])
For I in Range (linenum):
Begin = (Random.randint (0,self.size[0]), Random.randint (0,self.size[1))
End = (Random.randint (0,self.size[0]), Random.randint (0,self.size[1))
Draw.line ([Begin,end],fill = (0,0,0))
def createpoints (Self,draw):
"""
Usage: Create a scatter noise
Para:draw represents a brush
Return:none
For
Todo:
"""
#散点噪音
For x in range (Self.size[0]):
For y in range (self.size[1]):
Flag = Random.randint (0,self.pointborder[0])
If flag > Self.pointborder[1]:
Draw.point ((x,y), fill = (0,0,0))
Del flag
if __name__ = = ' __main__ ':
C=picchecker ()
T=c.createchecker ()
Print (t)