欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python制作验证码

程序员文章站 2022-07-02 16:36:13
from PIL import Image, ImageFont, ImageDraw, ImageFilterfrom random import choice, randint# 随即配置颜色def rand_color(): return (randint(128, 255), randint ......
from pil import image, imagefont, imagedraw, imagefilter
from random import choice, randint


# 随即配置颜色
def rand_color():
return (randint(128, 255), randint(128, 255), randint(128, 255))


# 创建图片
# img = image.new(格式,大小,颜色)
img = image.new('rgb', (200, 50), 'white')

# 创建字体
font = imagefont.truetype('xdxwz.ttf', 30)

# 创建画笔,画出img展示出的东西
draw = imagedraw.draw(img)
# 展示
# img.show()
code = ''.join(choice('0123456789') for i in range(4))

# 画字
for i in range(4):
# xy:位置, text:文本字, fill:颜色,font:字体
draw.text(xy=(i * 50 + 15, 0), text=code[i], fill='black', font=font)

# 画干扰点
for i in range(200 * 50):
x = randint(0, 199)
y = randint(0, 49)
# xy:位置 , fill:颜色
draw.point(xy=(x, y), fill=rand_color())
#模糊处理,没啥事别加
# img = img.filter(imagefilter.gaussianblur)
img.show()
# 保存文本
img.save('{}.png'.format(code))
# 看一眼
print(code)