Python writes a verification code that pulls pictures to match

To implement a verification code that pulls pictures to match, the following steps are required:

  1. Generate a random captcha image
  2. Generate a background image corresponding to the verification code image
  3. Merge background image and captcha image
  4. Randomly generate a set of coordinates for cutting the verification code picture
  5. Display the cut verification code picture on the page
  6. Monitor user input to determine whether it matches the correct verification code

Here is a simple Python implementation:

pythonimport random
import string
from PIL import Image, ImageDraw

# 生成随机验证码图片
def generate_code_image(width, height, code):
img = Image.new('RGB', (width, height), (255, 255, 255))
draw = ImageDraw.Draw(img)
draw.text((10, 10), code, font=ImageFont.truetype('arial.ttf', 36), fill=(0, 0, 0))
return img

# 生成与验证码图片相对应的背景图片
def generate_background_image(width, height):
img = Image.new('RGB', (width, height), (255, 255, 255))
draw = ImageDraw.Draw(img)
for i in range(random.randint(5, 10)):
x1 = random.randint(0, width // 2)
y1 = random.randint(0, height // 2)
x2 = random.randint(width // 2, width)
y2 = random.randint(height // 2, height)
draw.line((x1, y1, x2, y2), fill=(0, 0, 0), width=2)
return img

# 将背景图片和验证码图片合并
def merge_images(background_img, code_img):
width = background_img.width + code_img.width
height = max(background_img.height, code_img.height)
result = Image.new('RGB', (width, height), (255, 255, 255))
result.paste(background_img, (0, 0))
result.paste(code_img, (background_img.width, 0))
return result

# 随机生成一组坐标,用于将验证码图片进行切割
def generate_coords(width, height):
x1 = random.randint(0, width // 2 - 10)
y1 = random.randint(0, height // 2 - 10)
x2 = random.randint(width // 2 + 10, width)
y2 = random.randint(height // 2 + 10, height)
return (x1, y1, x2, y2)

# 将切割后的验证码图片显示在页面上
def show_code_image(code_img):
code_img.show()

# 监听用户输入,判断是否与正确的验证码匹配
def check_code(user_input, correct_code):
return user_input == correct_code

# 主程序
if __name__ == '__main__':
# 生成随机的验证码和背景图片
code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=4))
background_img = generate_background_image(400, 100)
code_img = generate_code_image(200, 50, code)
# 将验证码图片和背景图片合并
merge_img = merge_images(background_img, code_img)
# 显示合并后的图片并等待用户输入
show_code_image(merge_img)
user_input = input('请输入验证码:')

Guess you like

Origin blog.csdn.net/ducanwang/article/details/131895052