Generate Graphic Verification Code Using Python Captcha Module

The captcha module is a Python third party library designed to generate graphic and speech captcha codes. The graphic verification code supports Numbers and English words.

1. Captcha Module Installation.

You can use the pip command to install it directly or go to it’s project github page to download it. As the captcha module use the PIL module to generate pictures, it is necessary to install the PIL module for normal use.

2. Generate Verification Code.

The image verification code is generated using the ImageCaptcha class in the image module.

# Import ImageCaptcha class.
from captcha.image import ImageCaptcha

# Create a new ImageCaptcha instance.
img = ImageCaptcha()

# Generate image with the text python.
image = img.generate_image('python')

# Display the image

# Save the image to a file.'python.jpg')

captcha verification code text image

3. ImageCaptcha Class Introduction.

3.1 Constructor Method.

ImageCaptcha(width=160, height=60, fonts=None, font_sizes=None)

  1. width: width of the generate captcha image, default is 160 pixels.
  2. height: the height of the verification code image, default is 60 pixels.
  3. fonts: font file path, font used to generate authentication code, By default, the module comes with a DroidSansMono.ttf font. You can put the font file into the list or tuple and use it randomly when generating the verification code.
  4. font_sizes: controls the text font size of the captcha, like fonts, receives a list or tuple of font size and use the size randomly.

3.2 generate_image(chars) .

The core method of generating the verification code, generate the Image object of the verification code use chars content.

3.3 create_captcha_image(chars, color, background).

The implementation method of generate_image, can be overridden to implement custom captcha styles.

3.4 create_noise_dots(image, color, width=3, number=30).

Generate verification code interference points.

3.5 create_noise_curve(image, color).

Generate the verification code interference curve.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.