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 uses 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 image.show() # Save the image to a file. image.save('python.jpg')
- Below is the captcha image that is generated in this example.
3. ImageCaptcha Class Introduction.
3.1 Constructor Method.
- ImageCaptcha(width=160, height=60, fonts=None, font_sizes=None).
- width: width of the generate captcha image, default is 160 pixels.
- height: the height of the verification code image, default is 60 pixels.
- 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.
- 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) .
- 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).
- 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).
- Generate verification code interference points.
3.5 create_noise_curve(image, color).
- Generate the verification code interference curve.