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.

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

2. Generate Verification Code.

  1. 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
    image.show()
    
    # Save the image to a file.
    image.save('python.jpg')
  2. Below is the captcha image that is generated in this example.
    captcha-verification-code-text-image

 

3. ImageCaptcha Class Introduction.

3.1 Constructor Method.

  1. ImageCaptcha(width=160, height=60, fonts=None, font_sizes=None).
  2. width: width of the generate captcha image, default is 160 pixels.
  3. height: the height of the verification code image, default is 60 pixels.
  4. fonts: specify the font file path, the 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.
  5. font_sizes: controls the text font size of the captcha, like fonts, receives a list or tuple of font size and uses the size randomly.

3.2 generate_image(chars) .

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

3.3 create_captcha_image(chars, color, background).

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

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

  1. Generate verification code interference points.

3.5 create_noise_curve(image, color).

  1. 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.