第 0010 题:使用 Python 生成类似于下图中的字母验证码图片
思路:
1. 随机生成字符串
2. 创建画布往上头写字符串
3. 干扰画面
code:
# codeing: utf-8 from PIL import Image, ImageDraw, ImageFont, ImageFilter import string import random def get4char(): return [random.choice(string.ascii_letters) for _ in range(4)] # 可以把‘_’换做任意字母,‘_’说明后续不用 def getcolor(): return random.randint(30, 100), random.randint(30, 100), random.randint(30, 100) def getpicture(): width = 240 height = 60 image = Image.new('RGB', (width, height), (180, 180, 180)) font = ImageFont.truetype('arial.ttf', 40) draw = ImageDraw.Draw(image) code = get4char() for ch in range(4): draw.text((60 * ch,30), code[ch], font=font, fill=getcolor()) for _ in range(random.randint(1500, 3000)): draw.point((random.randint(0, width), random.randint(0, height)), fill=getcolor()) image = image.filter(ImageFilter.BLUR) image.save("".join(code) + '.jpg') getpicture()
Notes:
1. string.ascii_letters,大小写英文字母集合字符串
2. random.choice():Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError
.
3. random.randint():Return a random integer N such that a <= N <= b
. Alias for randrange(a, b+1)
.
4. image.new('RGB', (w,h), (r,g,b))
result:
我觉得自己应该去把tutorial从头到尾先看一遍= - =
下一篇写怎么识别验证码咯。