Python picture Captcha code sharing

Source: Internet
Author: User
Copy CodeThe code is as follows:


#coding: Utf-8
Import Image,imagedraw,imagefont,os,string,random,imagefilter
Def initchars ():
"""
Allowed set of characters, initial collection is numeric, uppercase and lowercase
Usage:initchars ()
Param:none
Return:list
Returns the allowed character set and
For:picchecker class Initial Character set
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) User registration needs to fill in the picture verification code, to prevent the robot registration
2) The number of image Captcha characters is 4 bits (uppercase and lowercase letters and numbers, case-insensitive).
If the user does not fill in the verification code or does not fill in the correct verification code,
Page-friendly prompts the user to fill in (at the same time the program also makes corresponding restrictions)
USAGE:PC = Picchecker (). Createchecker ()
Param: Many, as follows
Chars allowed character sets,
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
Begin character position, that is, the upper-left corner position
Type Tutle
Default value (5,-2)
OutputType Output Type
Type string
Default Value GIF
Optional value GIF JPEG TIFF PNG
Mode picture modes
Type string
Optional value RGB L (there are other modes, but only recommended for these 2 types)
Default Value RGB
BackgroundColor background Color
Foregroundcolor Front View
When Mode=rgb, Backgroundcolor,foregroundcolor is the Tutle type
Value is (Integer,integer,integer)
Represents an RGB color value
When Mode=l, Backgroundcolor,foregroundcolor is a number indicating black and white mode
Value is 0-255
Represents grayscale
Fonttype Font Path
Type string
Default value "SIMSUM.TTC"
Jamnum Number of interfering lines
Type (INT1,INT1)
Int1 the lower limit of the number of interfering lines, including
Int2 line number of interference lines, including
Pointborder scattered noise.
Construction method: Use random function for each pixel to determine if scatter noise is drawn on the pixel.
Type (INT1,INT2)
The bigger the int1, the more scatter.
The bigger the int2, the less scatter.
return: [Piccheckerstr,pic]
PICCHECKERSTR: Indicates that the corresponding string in the picture is returned and can be used for session validation and other purposes
Pic: returned picture, type 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 = (),
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: Generates a random string 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: the 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)/100,
0,
0,
0,
1-float (Random.randint (1,10))/100,
Float (random.randint)/500,
0.001,
Float (random.randint)/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 interference lines
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 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)
  • Related Article

    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.