PIL实现验证码的生成
PIL:Python Imaging Library,已经是Python平台事实上的图像处理标准库了。PIL功能非常强大,但API却非常简单易用。
安装PIL
在Debian/Ubuntu Linux下直接通过apt安装:
$ sudo apt-get install python-imaging
Mac和其他版本的Linux可以直接使用easy_install或pip安装,安装前需要把编译环境装好:
$ sudo easy_install PIL
如果安装失败,根据提示先把缺失的包(比如openjpeg)装上。
Windows平台就去PIL官方网站下载exe安装包。
!!!注意!!!
在python3上安装PIL时如果现实找不到PIL包则安装pillow
代码实现:
from PIL import Image,ImageDraw,ImageFont #导入所需要的图片处理包
import random #随机数
import io #输入输出流
class yanzhengma:
def __init__(self): #初始化类
self.width=100
self.height=35
self.lineNum=0
self.pointNum=0
self.im=None
self.codeCon="abcdefhjkmn2345678ABCDEFGHJKLMN" #随机显示出来的验证码内容
self.codeNum=4
self.str=""
self.currColor = self.bgColor()
def bgColor(self): #背景色
return (random.randint(0,100),random.randint(0,100),random.randint(0,100),255)
def fgColor(self): #前景色
return (random.randint(140,255),random.randint(140,255),random.randint(140,255),255)
def createImage(self): #创建图片对象
self.im=Image.new("RGBA",(self.width,self.height),color=self.currColor)
def drawLines(self): #在图片上画线
lineNum=self.lineNum or random.randint(5,10)
draw=ImageDraw.Draw(self.im)
for i in range(lineNum):
draw.line((random.randint(0,self.width),random.randint(0,self.height),random.randint(0,self.width),random.randint(0,self.height)),fill=self.fgColor(),width=random.randint(1,2))
def state(self): #旋转
self.im=self.im.rotate(random.randint(-10, 10))
im1 = Image.new("RGBA", (self.width, self.height), color=self.currColor)
self.im=Image.composite(self.im,im1,self.im)
def drawText(self): #在图片上加上字
fon=ImageFont.truetype('C:\Windows\Fonts\simhei.ttf', 30)
draw = ImageDraw.Draw(self.im)
for i in range(self.codeNum):
ranNum = random.randint(-7, 7)
x=i*(self.width/self.codeNum)+ranNum
con = self.codeCon[random.randint(0, len(self.codeCon) - 1)]
self.str+=con.lower()
draw.text((x,ranNum),con,fill=self.fgColor(),font = fon)
self.state()
def drawPoint(self): #在图片上生成随机的点
pointNum = self.pointNum or random.randint(30, 60)
draw = ImageDraw.Draw(self.im)
for j in range(pointNum):
draw.point((random.randint(0,self.width),random.randint(0,self.height)),fill=self.fgColor())
def output(self):
self.createImage()
self.drawLines()
self.drawPoint()
self.drawText()
bt=io.BytesIO()
# self.im.show()
self.im.save(bt,"png")
return bt.getvalue()