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)