Python Pillow库的简单使用
使用Python生成一张用于登陆验证的字符图片, 代码使用了Pillow,Anaconda已经默认安装此库,如果你使用的是官方版的Python需要先下载此库。
代码如下,在注释中予以说明:
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
#定义一个生成随机字符的函数 ASII码表 48-57: 0-9 65-90: A-Z 97-122: a-z
def randChar():
i = random.randint(0, 2)
if i == 0:
return chr(random.randint(65, 90)) #大写字符
elif i == 1:
return chr(random.randint(97, 122)) #小写字符
else:
return chr(random.randint(48,57)) #数字
#定义一个生成图片的颜色(颜色尽量浅,以免字符用户都看不清楚)
def randColor1():
return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))
#再定义一个生成字体的颜色(颜色尽量深,在尽可能无法被机器识别的前提下,让用户看清楚)
def randColor2():
return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
#生成图片宽度
width = 60 * 8
#生成图片高度
height = 60
#创建image对象
image = Image.new('RGB', (width, height), (255, 255, 255))
#创建Font对象
font = ImageFont.truetype('arial.ttf', 36)
#创建Draw对象
draw = ImageDraw.Draw(image)
#画图
for x in range(width):
for y in range(height):
draw.point((x, y), fill = randColor1())
#point两个参数 第一个是坐标(tuple) 第二个是颜色(C语言3个,横纵坐标算2个)
#加字
for t in range(8):
draw.text((60 * t + random.randint(0, 9) * randomrandint(0,5), random.randint(0, 9)), randChar(), font = font, fill = randColor2())
#draw.text 4个参数 坐标 字符 字体 颜色
#第一个参数大量使用randint 尽可能使得字变得散
#添加模糊效果
image = image.filter(ImageFilter.BLUR)
image.save('code.jpg', 'jpeg')
有可以改进的地方,把import random
改成 from random import randint
就可以不在randint
指明random了。
无注释纯净版:
from PIL import Image, ImageDraw, ImageFont, ImageFilter
from random import randint
def randChar():
i = randint(0, 2)
if i == 0:
return chr(randint(65, 90))
elif i == 1:
return chr(randint(97, 122))
else:
return chr(randint(48,57))
def randColor1():
return (randint(64, 255), randint(64, 255), randint(64, 255))
def randColor2():
return (randint(32, 127), randint(32, 127), randint(32, 127))
width = 60 * 8
height = 60
image = Image.new('RGB', (width, height), (255, 255, 255))
font = ImageFont.truetype('arial.ttf', 36)
draw = ImageDraw.Draw(image)
for x in range(width):
for y in range(height):
draw.point((x, y), fill = randColor1())
for t in range(8):
draw.text((60 * t + randint(0, 9) * randint(0,5), randint(0, 9)), randChar(), font = font, fill = randColor2())
image = image.filter(ImageFilter.BLUR)
image.save('code.jpg', 'jpeg')
结果: