1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| """ 使用 Python 生成类似于下图中的字母验证码图片。 """
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random import string
def rndChar(): return random.choice(string.ascii_letters)
def bkgColor(): return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))
def charColor(): return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
width = 60 * 4 height = 60 image = Image.new('RGB', (width, height), (255, 255, 255))
font = ImageFont.truetype('consolab.ttf', 42)
draw = ImageDraw.Draw(image)
for x in range(width): for y in range(height): draw.point((x, y), fill=bkgColor())
letters = [] for t in range(4): char = rndChar() letters.append(char) draw.text((60 * t + random.randint(10,20), random.randint(10,20)),char, font=font, fill=charColor())
image = image.filter(ImageFilter.BLUR) image.save('code.png')
print(letters) image.show()
|