Skip to content

Instantly share code, notes, and snippets.

@mahdizojaji
Created July 21, 2021 13:04
Show Gist options
  • Save mahdizojaji/5c14b815196330fba86316fd88436500 to your computer and use it in GitHub Desktop.
Save mahdizojaji/5c14b815196330fba86316fd88436500 to your computer and use it in GitHub Desktop.
Generate captcha image
def create_captcha_image() -> List[Union[BytesIO, str]]:
def rand_color_one():
return random.randint(64, 255), random.randint(64, 255), random.randint(64, 255)
def rand_color_two():
return random.randint(32, 127), random.randint(32, 127), random.randint(32, 127)
def rand_str():
result = [
random.choice([chr(_) for _ in range(1570, 1595)]),
random.choice([chr(_) for _ in range(1570, 1595)]),
random.choice([chr(_) for _ in range(1777, 1786)]),
random.choice([chr(_) for _ in range(1777, 1786)]),
# random.choice([chr(_) for _ in range(97, 123)]),
# random.choice([str(_) for _ in range(0, 10)]),
]
random.shuffle(result)
return result
width = 512
height = 512
image = Image.new('RGB', (width, height), (255, 255, 255))
font = ImageFont.truetype(r'Sahel.ttf', 100)
draw = ImageDraw.Draw(image)
for x in range(width):
for y in range(height):
draw.point((x, y), fill=rand_color_one())
text = rand_str()
draw.text((30, 170), text[0], rand_color_two(), font=font, align='center')
draw.text((150, 170), text[1], rand_color_two(), font=font, align='center')
draw.text((270, 170), text[2], rand_color_two(), font=font, align='center')
draw.text((390, 170), text[3], rand_color_two(), font=font, align='center')
output = BytesIO()
image.save(output, format='jpeg')
return [output, ' '.join(text), ' '.join(rand_str()), ' '.join(rand_str()), ' '.join(rand_str())]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment