本项目采用的是https://github.com/Yixiaohan/show-me-the-code中所提供的练习项目,所有代码均为原创,转载请注明,谢谢。
问题描述:使用 Python 生成类似于下图中的字母验证码图片
# -*- coding: utf-8 -*-
"""Created on Wed Jan 11 12:48:02 2017
@author: sky
"""
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
import string
IMAGE_MODE = 'RGB'
IMAGE_BG_COLOR = (255,255,255)
Image_Font = 'arial.ttf'
chars = string.letters + string.digits
text = ''.join(random.sample(chars,10))
def colorRandom():
return (random.randint(32,127),random.randint(32,127),random.randint(32,127))
#change 噪点频率(%)
def create_identifying_code(strs, width=1080, height=800, chance=2):
im = Image.new(IMAGE_MODE, (width, height), IMAGE_BG_COLOR)
draw = ImageDraw.Draw(im)
#绘制背景噪点
for w in xrange(width):
for h in xrange(height):
if chance < random.randint(1, 100):
draw.point((w, h), fill=colorRandom())
font = ImageFont.truetype(Image_Font, 100)
font_width, font_height = font.getsize(strs)
strs_len = len(strs)
x = (width - font_width)/2
y = (height - font_height)/2
#逐个绘制文字
for i in strs:
draw.text((x,y), i, colorRandom(), font)
x += font_width/strs_len
#模糊
im = im.filter(ImageFilter.BLUR)
im.save('identifying_code_pic.jpg')
if __name__ == '__main__':
create_identifying_code(text)
详细代码和结果,可以参考https://github.com/g8015108/exercise-for-python