Python使用PIL模块生成随机验证码

时间:2022-11-30 16:46:18

PIL模块的安装

pip3 install pillow

生成随机验证码图片

import random
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO def random_str():
'''
生成随机字符
:return:随机字符
'''
random_int = str(random.randint(0,9))
random_up = chr(random.randint(65,90))
random_down = chr(random.randint(97,122))
retu_str = random.choice([random_int,random_up,random_down])
return retu_str def rndColor():
'''
生成随机颜色
:return: 随机rbg颜色
'''
return (random.randint(0, 255), random.randint(10, 255), random.randint(64, 255))
def get_verify_code_img(filename):
'''
生成随机验证码图片,保存到内存,通过HttpResponse发送到前端
:param request: 生成session
:return: 内存中的图片
''' # 创建图片与画笔
img = Image.new(mode='RGB',size=(186,34),color=rndColor())
draw = ImageDraw.Draw(img)
verify = '' # 字体样式
font = ImageFont.truetype(font='font1.ttf',size=20) #生成六位数验证码
for i in range(6):
char = random_str()
verify += char
draw.text([i*20+50,5],char,font=font,fill=rndColor()) f = open(filename','wb')
img.save(f,'png')

还可以给图片验证码添加燥点与燥线

将下面代码添加到get_verify_code_img中

    # width=270
# height=40
# for i in range(10):
# 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())

调用

get_verify_code_img('验证码.png')