Site icon FSIBLOG

How To Create An Image Captcha Generator In Python

Recently, I had the opportunity to work on a fun and practical project for a client: creating a CAPTCHA generator in Python. CAPTCHAs are an essential part of website security, ensuring human interaction while keeping bots at bay. I wanted to take this a step further, not just generating random CAPTCHA images but building something interactive, reusable, and customizable.

Build a CAPTCHA Generator

As a developer, I enjoy building practical projects that solve real-world problems. CAPTCHAs are widely used for security, and learning how to generate them not only helps you understand their mechanics but also equips you with a valuable skill for creating secure applications.

I wanted to go beyond just generating random CAPTCHA images I wanted to make it interactive, reusable, and easy to customize.

The Complete Python Code

Here’s the complete code for generating CAPTCHA images with enhanced functionality, such as user validation, folder management, and configurable settings.

codefrom captcha.image import ImageCaptcha
import random
import os

# Function to 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

# Function to create a CAPTCHA image
def create_captcha_image(output_folder, image_width=450, image_height=100, captcha_length=6):
# Ensure output folder exists
if not os.path.exists(output_folder):
os.makedirs(output_folder)

# Generate random CAPTCHA text
captcha_text = generate_random_captcha_text(length=captcha_length)

# Create CAPTCHA image
image = ImageCaptcha(width=image_width, height=image_height)
image_file_path = os.path.join(output_folder, f'{captcha_text}.png')
image.write(captcha_text, image_file_path)

return captcha_text, image_file_path

# Function to validate user input against CAPTCHA text
def validate_captcha(captcha_text):
user_input = input("Enter the CAPTCHA text displayed in the image: ")
if user_input == captcha_text:
print("CAPTCHA validated successfully!")
else:
print("Incorrect CAPTCHA. Try again.")

# Main functionality
def main():
# Settings
output_folder = 'captchas'
captcha_count = 3 # Number of CAPTCHAs to generate

for _ in range(captcha_count):
captcha_text, image_path = create_captcha_image(output_folder)
print(f"CAPTCHA text: {captcha_text}")
print(f"CAPTCHA image saved at: {image_path}")

# Prompt the user to validate the CAPTCHA
validate_captcha(captcha_text)

if __name__ == "__main__":
main()

Key Explain

Here’s how I enhanced the code to make it more practical:

Dynamic CAPTCHA Length & Image Size

Output Folder Management

Multiple CAPTCHA Generation

CAPTCHA Validation

Reusability

How It Works

Install the Required Library

Before running the script, make sure to install the captcha library:

codepip install captcha

Run the Script

When you execute the script, it generates a specified number of CAPTCHA images and saves them in the captchas folder.

User Interaction

After each CAPTCHA is generated, the user is prompted to enter the text displayed in the CAPTCHA image. The script then validates the input and provides feedback.

Step-by-Step Execution

Here’s what happens when you run the script:

  1. Generate CAPTCHA Text:
    • Random text (letters and numbers) is created using the generate_random_captcha_text function.
  2. Create CAPTCHA Image:
    • The text is rendered into an image using the ImageCaptcha class from the captcha library.
  3. Save the Image:
    • The image is saved to the specified folder with the CAPTCHA text as its filename (e.g., ABC123.png).
  4. Validate User Input:
    • The script asks you to type the text displayed in the CAPTCHA image and validates your input.

Customization Options

Here are a few ways you can customize the script to suit your needs:

  1. Change CAPTCHA Text Length:
    • Modify the captcha_length parameter in the create_captcha_image function.
  2. Adjust Image Dimensions:
    • Change the image_width and image_height parameters for different-sized CAPTCHA images.
  3. Generate More CAPTCHAs:
    • Increase the captcha_count variable in the main function to generate more images in one run.

Challenges & Solutions

Final Thoughts

Building this CAPTCHA generator was a great learning experience. It allowed me to explore Python’s capabilities and work on a security-focused project. If you try this out, feel free to tweak the code to add your own features, such as different font styles or noise patterns in the images.

Exit mobile version