安装:
pip install pillow
基本使用,如果想直接要生成验证码的代码这步可跳过:
from PIL import Image,ImageDraw
#创建一张宽高为120x30 颜色是255,255,255的图片
img = Image.new(mode='RGB',size=(120,30),color=(255,255,255))
with open('code.png','wb') as f:
img.save(f,format='png')
#创建画笔,用于在图片上画任意内容
draw = ImageDraw.Draw(img,mode='RGB')
#画点 point(self, xy, fill=None)
draw.point([100,20],fill='red')
draw.point([20,30],fill=(255,255,255))
#画线 line(self, xy, fill=None, width=0, joint=None): xy是起始坐标和结束坐标
draw.line([100,10,100,30],fill='red',width=2)
#画圆 arc(self, xy, start, end, fill=None, width=1): 第一个参数表示圆要画在哪个图形中间的起始坐标和结束坐标,第二个参数表示开始角度,第三个结束角度,第四个表示颜色
draw.arc([100,100,300,300],0,90,fill='red')
#写文本 xy,text, fill=None, font=None, anchor=None, spacing=4, align="left", xy起始点坐标
draw.text((10,10),'hello world','red')
#写特殊字体 在写文本的基础上设置字体
font = ImageFont.truetype('KumoFont.ttf',28)
draw.text((10,10),'hello world','red',font=font)
封装好的随机验证码代码
from PIL import Image,ImageDraw,ImageFont,ImageFilter
import random
import os
def check_code(width=120, height=30, char_length=5, font_file=r'\app01\static\font\kumo.ttf', font_size=28,project_name = ''):
# 获取文件目录
curPath = os.path.abspath(os.path.dirname(__file__))
# 获取项目根路径,内容为当前项目的名字
rootPath = curPath[:curPath.find(project_name) + len(project_name)]
font_file =rootPath + font_file
code = []
img = Image.new(mode='RGB', size=(width, height), color=(255, 255, 255))
draw = ImageDraw.Draw(img, mode='RGB')
def rndChar():
"""
生成随机字母
:return:
"""
return chr(random.randint(65, 90)) #65-90是大写字母 97-122是小写字母 48-57是0-9
def rndColor():
"""
生成随机颜色
:return:
"""
return (random.randint(0, 255), random.randint(10, 255), random.randint(64, 255))
# 写文字
font = ImageFont.truetype(font_file, font_size)
for i in range(char_length):
char = rndChar()
code.append(char)
h = random.randint(0, 4)
draw.text((i * width / char_length, h), char, font=font, fill=rndColor())
# 写干扰点
for i in range(40):
draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())
# 写干扰圆圈
for i in range(40):
draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())
x = random.randint(0, width)
y = random.randint(0, height)
draw.arc((x, y, x + 4, y + 4), 0, 90, fill=rndColor())
# 画干扰线
for i in range(5):
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=rndColor())
img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
return img, ''.join(code)
if __name__ == '__main__':
# 1. 直接打开
# img,code = check_code()
# img.show()
# 2. 写入文件
# img,code = check_code()
# with open('code.png','wb') as f:
# img.save(f,format='png')
# 3. 写入内存(Python3)
# from io import BytesIO
# stream = BytesIO()
# img.save(stream, 'png')
# stream.getvalue()
# 4. 写入内存(Python2)
# import StringIO
# stream = StringIO.StringIO()
# img.save(stream, 'png')
# stream.getvalue()
pass
调用:
from app01.utils.code import check_code
img,img_str = check_code(font_file=r'字体文件路径',project_name='项目名称')
print(img_str)