第 0010 题: 使用 Python 生成类似于下图中的字母验证码图片
1 from PIL import Image, ImageDraw, ImageFont, ImageFilter 2 from random import randint 3 4 def rnd_char(): #生成随机数字或字母 5 tmp = randint(1,3) #前者是下限,后者是上限 6 if tmp == 1: 7 return randint(48,57) 8 elif tmp == 2: 9 return randint(65,90) 10 else: 11 return randint(97,122) 12 13 w = 250 14 h = 50 15 im = Image.new('RGB', (w,h), (255,255,255)) 16 font = ImageFont.truetype('C:/windows/fonts/Arial.ttf', 30) 17 draw = ImageDraw.Draw(im) 18 19 for i in range(w): #一个一个像素点填充 20 for j in range(h): 21 draw.point((i, j), fill = (randint(130,255),randint(130,255),randint(130,255))) 22 23 for i in range(4): #添加验证码 24 draw.text((50*(i+1),5), chr(rnd_char()), font = font, fill = (randint(0,255),randint(0,255),randint(0,255))) 25 im = im.filter(ImageFilter.BLUR) # 模糊处理 26 27 im.show()