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
- The code allows you to configure the CAPTCHA text length, image width, and height. This ensures flexibility in generating CAPTCHAs that fit different use cases.
Output Folder Management
- The script ensures that CAPTCHA images are saved in a dedicated folder (
captchas
by default). If the folder doesn’t exist, it’s created automatically.
Multiple CAPTCHA Generation
- Instead of generating just one CAPTCHA, you can create multiple CAPTCHAs in one run by setting the
captcha_count
variable.
CAPTCHA Validation
- To simulate a real-world scenario, the script prompts the user to enter the CAPTCHA text they see in the image. It checks if the input matches the CAPTCHA text and provides feedback.
Reusability
- The functions are modularized, making it easy to reuse or modify parts of the code for other projects.
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:
- Generate CAPTCHA Text:
- Random text (letters and numbers) is created using the
generate_random_captcha_text
function.
- Random text (letters and numbers) is created using the
- Create CAPTCHA Image:
- The text is rendered into an image using the
ImageCaptcha
class from thecaptcha
library.
- The text is rendered into an image using the
- Save the Image:
- The image is saved to the specified folder with the CAPTCHA text as its filename (e.g.,
ABC123.png
).
- The image is saved to the specified folder with the CAPTCHA text as its filename (e.g.,
- 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:
- Change CAPTCHA Text Length:
- Modify the
captcha_length
parameter in thecreate_captcha_image
function.
- Modify the
- Adjust Image Dimensions:
- Change the
image_width
andimage_height
parameters for different-sized CAPTCHA images.
- Change the
- Generate More CAPTCHAs:
- Increase the
captcha_count
variable in themain
function to generate more images in one run.
- Increase the
Challenges & Solutions
- Challenge: Saving images with unique names.
- Solution: Use the CAPTCHA text as the filename to ensure uniqueness.
- Challenge: User-friendly validation.
- Solution: Add a simple input prompt and comparison logic to validate user input.
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.