Python生成验证码
1.Python3.x中安装Pillow模块
pip install pillow
2.Python生成验证码(Python生成数字英文验证码, Python生成验证码,文章摘自: https://www.cnblogs.com)
'''
PIL(Python Imaging Library)是Python一个强大方便的图像处理库,名气也比较大。不过只支持到Python 2.7
在Python2中,PIL(Python Imaging Library)是一个非常好用的图像处理库,但PIL不支持Python3,所以有人(Alex Clark和Contributors)提供了Pillow,可以在Python3中使用。
Python3.x中安装Pillow模块:
pip install pillow
'''
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
import string
#生成4位验证码
def geneText():
return ''.join(random.sample(string.ascii_letters + string.digits, 4)) #ascii_letters是生成所有字母 digits是生成所有数字0-9
#随机颜色
def rndColor():
return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
def drawLines(draw, num, width, height):
'''划线'''
for num in range(num):
x1 = random.randint(0, width / 2)
y1 = random.randint(0, height / 2)
x2 = random.randint(0, width)
y2 = random.randint(height / 2, height)
draw.line(((x1, y1), (x2, y2)), fill='black', width=1)
#生成验证码图形
def getVerifyCode():
code = geneText()
# 图片大小120×50
width, height = 120, 50
# 新图片对象
im = Image.new('RGB', (width, height), 'white')
# 字体库文件
font = ImageFont.truetype('arial.ttf', 40)
# draw对象
draw = ImageDraw.Draw(im)
# 绘制字符串
for item in range(4):
draw.text((5 + random.randint(-3, 3) + 23 * item, 5 + random.randint(-3, 3)),text=code[item], fill=rndColor(), font=font)
# 划线
drawLines(draw, 2, width, height)
im.save('code.jpg', 'jpeg')# 将生成的图片保存为code.jpg
im.show()# 显示图片,第一次可能会提示选择默认图片查看器。
print(im,code)
return im, code
if __name__ == '__main__':
getVerifyCode()

浙公网安备 33010602011771号