1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| import random from PIL import Image, ImageDraw, ImageFont
def random_color(): return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
def random_char(length): characters = "023456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ" code = ''.join(random.choice(characters) for i in range(length)) return code
def generate_captcha(): width, height = 160, 60 image = Image.new("RGB", (width, height), (255, 255, 255)) draw = ImageDraw.Draw(image) font = ImageFont.truetype("arial.ttf", 36)
code = random_char(4) for idx,t in enumerate(code): draw.text((40 * idx + 10, 10), t, font=font, fill=random_color())
for x in range(0,width,10): for y in range(0,height,10): draw.point((x, y), fill=(0,0,0))
for i in range(3): x1 = random.randint(0, width) y1 = random.randint(0, height) x2 = random.randint(0, width) y2 = random.randint(0, height) draw.line((x1, y1, x2, y2), fill=(0, 0, 0), width=2) image.save("captcha.jpg", "jpeg")
generate_captcha()
|