思路:
1、画一张白色的图片(大小为:200*50)
2、逐个填充像素点,每个像素点随机
3、往图片上写入字符
- 字符随机生成
- 字符的颜色是随机的
- 字符的组成:大写字母、小写字母以及数字
from PIL import Image, ImageDraw, ImageFont
import numpy as np
def bgcolor():
return np.random.randint(64, 255), np.random.randint(64, 255), np.random.randint(64, 255)
def randomtxt():
txt_list = []
txt_list.extend([i for i in range(65,91)])
txt_list.extend([i for i in range(97,123)])
txt_list.extend([i for i in range(48,58)])
return chr(txt_list[np.random.randint(0, len(txt_list)-1)])
def txtcolor():
return np.random.randint(32, 127), np.random.randint(32, 127), np.random.randint(32, 127)
def generatecode():
width = 200
height = 50
image = Image.new('RGB', (width, height), (255, 255, 255))
draw = ImageDraw.Draw(image)
for w in range(width):
for h in range(height):
draw.point((w, h),fill=bgcolor())
myfont = ImageFont.truetype('arial.ttf', 36)
for i in range(4):
draw.text((50*i+10,10), randomtxt(), font=myfont, fill=txtcolor())
image.show()
image.save(r'./res/验证码.png','PNG')
generatecode()