用 Python制作图片验证码?也就三行代码罢了
Pillow库
1、Image:含有图片对象主体上的一些应用 2、ImageDraw:画笔,用来向图片上添加验证码 3、ImageFont:设置验证码的字体形式 4、ImageFilter:对图片验证码进行模糊处理
from PIL import Image,ImageDraw,ImageFont,ImageFilter
import random,string
#获取随机4个字符组合
def getRandomChar():
chr_all = string.ascii_letters+string.digits
chr_4 = ''.join(random.sample(chr_all,4))
return chr_4
#获取随机颜色
def getRandomColor(low,high):
return (random.randint(low,high),random.randint(low,high),random.randint(low,high))
#制作验证码图片
def getPicture():
width,height = 180,60
#创建空白画布
image = Image.new('RGB',(width,height),getRandomColor(20,100))
#验证码的字体
font = ImageFont.truetype('C:/Windows/fonts/stxinwei.ttf',40)
#创建画笔
draw = ImageDraw.Draw(image)
#获取验证码
char_4 = getRandomChar()
#向画布上填写验证码
for i in range(4):
draw.text((40*i+10,0),char_4[i],font = font,fill=getRandomColor(100,200))
#绘制干扰点
for x in range(random.randint(200,600)):
x = random.randint(1,width-1)
y = random.randint(1,height-1)
draw.point((x,y),fill=getRandomColor(50,150))
#模糊处理
image = image.filter(ImageFilter.BLUR)
image.save('./%s.jpg' % char_4)
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
captcha库
pip install captcha -i https://pypi.tuna.tsinghua.edu.cn/simple
from captcha.image import ImageCaptcha
import random,string
chr_all = string.ascii_letters + string.digits
chr_4 = ''.join(random.sample(chr_all, 4))
image = ImageCaptcha().generate_image(chr_4)
image.save('./%s.jpg' % chr_4)
gvcode库
pip install graphic-verification-code -i https://pypi.tuna.tsinghua.edu.cn/simple
import gvcode
s,v = gvcode.generate()
s.save('./%s.jpg' % v)
print(type(s))
print(v)
print(type(v))
说在最后
更多阅读
特别推荐
点击下方阅读原文加入社区会员
评论