代码
# 没有混色
import string?
from random import randint, choice
from PIL import Image, ImageDraw, ImageFont
def generate_verification_code_image(self, length=6):
? ? from PIL import Image, ImageDraw, ImageFont
? ? import random
? ? import string
? ? # 1. 设定验证码长度和图片大小
? ? code_length = 6
? ? width, height = 200, 80
? ? # 2. 创建一个新的图像对象
? ? color = (randint(0, 255), randint(0, 255), randint(0, 255))
? ? image = Image.new('RGB', (width, height), color=color)
? ? # 3. 选择一种字体和字体大小
? ? # 这里假设你有一个.ttf字体文件,你需要指定其路径
? ? font_path = 'arial.ttf'? # 例如 'arial.ttf'
? ? font_size = 40
? ? # font = ImageFont.truetype(font_path, font_size)
? ? font = ImageFont.load_default(size=40)
? ? # 4. 随机生成6位包含数字和字母的验证码字符串
? ? characters = string.ascii_letters + string.digits? # 所有字母和数字
? ? code = ''.join(random.choice(characters) for _ in range(code_length))
? ? # 5. 在图像上绘制验证码字符串
? ? draw = ImageDraw.Draw(image)
? ? x = width // 4? # 起始位置
? ? y = height // 2 + font_size // 3? # 垂直居中,并稍微上移一些
? ? color = (randint(0, 255), randint(0, 255), randint(0, 255))
? ? draw.text((x, y), code, font=font, fill=color)
? ? # 6. 保存或显示图像
? ? # image.save('captcha.png')
? ? # image.show()
? ? return code, image
# 有混色
def generate_verification_code_image(self, length=6):
? ? width, height = 160, 50
? ? color = (randint(150, 255), randint(150, 255), randint(150, 255))
? ? image = Image.new('RGB', size=(width, height), color=color)
? ? font = ImageFont.load_default(size=40)
? ? draw = ImageDraw.Draw(image)
? ? code = ''.join(choice(string.ascii_letters + string.digits) for _ in range(length))
? ? for i, value in enumerate(code):
? ? ? ? color = (randint(0, 150), randint(0, 150), randint(0, 150))
? ? ? ? draw.text((5 + randint(4, 7) + 25 * i, 1 + randint(2, 8) + 2 * i),
? ? ? ? ? ? ? ? ? text=value,
? ? ? ? ? ? ? ? ? fill=color,
? ? ? ? ? ? ? ? ? font=font)
? ? for j in range(randint(5, 8)):
? ? ? ? x1 = randint(0, width)
? ? ? ? y1 = randint(0, height // 2)
? ? ? ? x2 = randint(0, width)
? ? ? ? y2 = randint(height // 2, height)
? ? ? ? color = (randint(0, 255), randint(0, 255), randint(0, 255))
? ? ? ? draw.line(((x1, y1), (x2, y2)), fill=color)
? ? for k in range(randint(5, 8)):
? ? ? ? start = (-height, -height)
? ? ? ? end = (width + 10, randint(0, height + 10))
? ? ? ? color = (randint(0, 255), randint(0, 255), randint(0, 255))
? ? ? ? draw.arc(start + end, 0, 360, fill=color)
? ? for m in range(width):
? ? ? ? for n in range(height):
? ? ? ? ? ? number = randint(1, 100)
? ? ? ? ? ? if number > 90:
? ? ? ? ? ? ? ? draw.point((m, n), fill=(randint(0, 255), randint(0, 255), randint(0, 255)))
? ? return code.lower(), image
参考: