Code:
from captcha.image import ImageCaptcha
import random
# Specify the image size
image = ImageCaptcha(width=450, height=100)
# Generate random captcha text
def generate_random_captcha_text(length=6):
characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
captcha_text = ''.join(random.choice(characters) for _ in range(length))
return captcha_text
# Get random captcha text
captcha_text = generate_random_captcha_text()
# Generate the image of the given text
data = image.generate(captcha_text)
# Write the image on the given file and save it
image.write(captcha_text, 'CAPTCHA1.png')
from PIL import Image
Image.open('CAPTCHA1.png')
#clcoding.com
Explanation:
This code snippet demonstrates how to automatically generate an image CAPTCHA using Python. Here's a breakdown of each part:
from captcha.image import ImageCaptcha: This imports the ImageCaptcha class from the captcha.image module. This class allows you to create CAPTCHA images.
import random: This imports the random module, which is used to generate random characters for the CAPTCHA text.
image = ImageCaptcha(width=450, height=100): This initializes an instance of the ImageCaptcha class with the specified width and height for the CAPTCHA image.
generate_random_captcha_text(length=6): This is a function that generates random CAPTCHA text. It takes an optional parameter length, which specifies the length of the CAPTCHA text. By default, it generates a text of length 6.
captcha_text = generate_random_captcha_text(): This calls the generate_random_captcha_text function to generate random CAPTCHA text and assigns it to the variable captcha_text.
data = image.generate(captcha_text): This generates the CAPTCHA image using the generated text. It returns the image data.
image.write(captcha_text, 'CAPTCHA1.png'): This writes the generated CAPTCHA image to a file named "CAPTCHA1.png" with the text embedded in the image.
from PIL import Image: This imports the Image class from the Python Imaging Library (PIL) module, which is used to open and display the generated CAPTCHA image.
Image.open('CAPTCHA1.png'): This opens the generated CAPTCHA image named "CAPTCHA1.png" using the PIL library.
Overall, this code generates a random CAPTCHA text, creates an image of the text using the ImageCaptcha class, saves the image to a file, and then displays the image using PIL.