需要安装第三方模块pillow
import random
from PIL import Image, ImageDraw, ImageFont
步骤一:编写一个生成随机颜色的函数
def get_random_color():
return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
步骤二:在面板里放入随机字符
width = 350
height = 38
img = Image.new("RGB", (width, height), get_random_color())
# 画一个随机颜色的面板
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("kumo.ttf", 32)
for i in range(6):
random_num = str(random.randint(0, 9))
random_low_alphabet = chr(random.randint(97, 122))
random_upper_alphabet = chr(random.randint(65, 90))
random_char = random.choice([random_num, random_low_alphabet, random_upper_alphabet])
# 在面板里画随机颜色的随机字符
draw.text((i * 30 + 55, 0), random_char, get_random_color(), font=font)
kumo.ttf是文字模型,可以从网上下载,博客上好像上传不了呀,无法分享出来了!!!!
步骤三:在面板上画随机线
for i in range(3):
x1 = random.randint(0, width)
x2 = random.randint(0, width)
y1 = random.randint(0, height)
y2 = random.randint(0, height)
draw.line((x1, y1, x2, y2), fill=get_random_color())
步骤四:在面板上画圆点
for i in range(100):
draw.point([random.randint(0, width), random.randint(0, height)], fill=get_random_color())
x = random.randint(0, width)
y = random.randint(0, height)
draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_random_color())
步骤五:将登录验证吗保存到本地文件
# 写与读
f = open("valid.jpg", "wb")
img.save(f, "png")
最后是生成下面图片中的样子
结尾附上完整代码
import random
from PIL import Image, ImageDraw, ImageFont
def get_valid_img():
def get_random_color():
return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
# 在面板里放入随机字符
width = 350
height = 38
img = Image.new("RGB", (width, height), get_random_color())
# 画一个随机颜色的面板
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("kumo.ttf", 32)
for i in range(6):
random_num = str(random.randint(0, 9))
random_low_alphabet = chr(random.randint(97, 122))
random_upper_alphabet = chr(random.randint(65, 90))
random_char = random.choice([random_num, random_low_alphabet, random_upper_alphabet])
draw.text((i * 30 + 55, 0), random_char, get_random_color(), font=font)
# 在面板上画随机线
for i in range(3):
x1 = random.randint(0, width)
x2 = random.randint(0, width)
y1 = random.randint(0, height)
y2 = random.randint(0, height)
draw.line((x1, y1, x2, y2), fill=get_random_color())
# 在面板上画圆点
for i in range(100):
draw.point([random.randint(0, width), random.randint(0, height)], fill=get_random_color())
x = random.randint(0, width)
y = random.randint(0, height)
draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_random_color())
# 写与读
f = open("valid.jpg", "wb")
img.save(f, "png")
if __name__ == '__main__':
get_valid_img()