Python image verification code sharing-Python tutorial

Source: Internet
Author: User
Tags image filter
Python image verification code sharing. For more information, see The code is as follows:

# Coding: UTF-8
Import Image, ImageDraw, ImageFont, OS, string, random, ImageFilter
Def initChars ():
Allowed character set combination. The initial set is numbers, uppercase and lowercase letters.
Usage: initChars ()
Param: None
Return: list
Returns the allowed character sets and
For: picChecker class initial character set combination
Todo: Nothing
Nums = [str (I) for I in range (10)]
LetterCase = [
'A', 'B', 'C', 'D', 'e', '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', '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) you must enter an image verification code to prevent robot registration.
2) the image verification code contains four characters (uppercase and lowercase letters and numbers, not case sensitive ).
If the user does not enter the verification code or does not enter the correct verification code,
Page friendliness prompts users to fill in (and restrictions are also imposed on the program)
Usage: pc = picChecker (). createChecker ()
Param: many, as shown below
Character Set combination allowed by chars,
Type list
Default value: initChars ()
Example ['1', '2', '3']
Length string length
Type integer
Default value: 4.
Size Image size
Type tutle
Default value)
Fontsize font size
Type integer
Default value: 25
The actual position of the begin character, that is, the position in 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 Image mode
Type string
Optional value: rgb l (other modes are available, but only the two modes are recommended)
Default value: RGB
BackgroundColor background color
ForegroundColor foreground color
When mode is RGB, backgroundColor and foregroundColor are tutle types.
The value is (integer, integer, integer)
RGB color value
When mode = L, backgroundColor and foregroundColor are numbers, indicating the black/white mode
Valid value: 0-255
Fonttype font path
Type string
Default value: "simsum. ttc"
JamNum interference line count
Type (int1, int1)
Minimum number of int1 interference lines, including
Int2 interference line number online, including
PointBorder scatter noise
Construction method: use a random function for each pixel to determine whether to draw scatter noise on the Pixel.
Type (int1, int2)
The larger the int1 value, the more scatter points it has.
The larger the value of int2, the less scattered points.
Return: [picCheckerStr, pic]
PicCheckerStr: returns the string corresponding to the image, which can be used for session verification and other purposes.
Pic: The Returned Image type.
Todo: Nothing
# Default font path
# 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 = (255 ),
Fonttype = "simsun. ttc", length = 4, jamNum = (1, 2 ),
PointBorder = (40, 39 )):
Initialize configuration
# Verification code configuration
# Allowed strings
Self. chars = chars
# Image size
Self. size = size
# Character start insertion point
Self. begin = begin
# String length
Self. length = length
# Output type
Self. outputType = outputType
# Character size
Self. fontsize = fontsize
# Image mode
Self. mode = mode
# Background color
Self. backgroundColor = backgroundColor
# Foreground
Self. foregroundColor = foregroundColor
# Number of interfering lines
Self. jamNum = jamNum
# Scatter noise limit
Self. pointBorder = pointBorder
# Library path
Self. fonttype = fonttype
# Set the font size. the default value is 18.
Self. font = ImageFont. truetype (self. fonttype, self. fontsize)
Def getPicString (self ):
Usage: getPicString ()
Return: string
For: generate a random string of a given length
Todo: Nothing
# Initialize the string length
Length = self. length
# Initializing character set combination
Chars = self. chars
# Get character set combination
SelectedChars = random. sample (chars, length)
CharsToStr = string. join (selectedChars ,'')
Return (charsToStr)
Def createChecker (self ):
Usage: createChecker ()
Return: [str, pic]
Str: corresponding string
Pic: corresponding image
# Obtain the verification code string
RandStr = self. getPicString ()
# Adding a string to a space
RandStr1 = string. join ([I + "" for I in randStr], "")
# Creating Images
Im = Image. new (self. mode, self. size, self. backgroundColor)
# Creating a paint brush
Draw = ImageDraw. Draw (im)
# Output random text
Draw. text (self. begin, randStr1, font = self. font, fill = self. foregroundColor)
# Im = self. drawText (draw, randStr, im)
# Interference line
Self. createJam (draw)
# Scatter noise
Self. createPoints (draw)
# Image distortion
Para = [1-float (random. randint (1, 2)/100,
1-float (random. randint (1, 10)/100,
Float (random. randint (1, 2)/500,
Float (random. randint (1, 2)/500
# Print randStr, para
Im = im. transform (im. size, Image. PERSPECTIVE, para)
# Image filter
Im = im. filter (ImageFilter. EDGE_ENHANCE_MORE)
Im. save ("checker.jpg", self. outputType)
Return ([randStr, im])
Def createJam (self, draw ):
Usage: creates interference lines.
Para: draw indicates the paint brush.
Return: None
# Number of interfering lines
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 ))
Def createPoints (self, draw ):
Usage: create scatter noise
Para: draw indicates the paint brush.
Return: None
# Scatter noise
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 ))
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: 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.