下面是一个实战项目的结果。
复制代码 代码如下:
import Image,ImageDraw,ImageFont,os,string,random,ImageFilter
def initChars():
"""
允许的字符集合,初始集合为数字、大小写字母
usage: initChars()
param: None
return: list
返回允许的字符集和
for: picChecker类初始字符集合
todo: Nothing
"""
nums = [str(i) for i in range(10)]
letterCase = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z'
]
upperCase = [
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z',
]
return(nums+letterCase+upperCase)
class picChecker():
"""
图片验证代码:
def init(self,chars = initChars(),size = (120,30),fontsize = 25,
begin = (5,-2),outputType = 'GIF',mode = 'RGB' ,
backgroundColor = (255,255,255), foregroundColor = (0,0,255),
fonttype = "simsun.ttc",length = 4,jamNum = (1,2),
pointBorder = (40,39)):
"""
初始化配置
"""
self.chars = chars
self.size = size
self.begin = begin
self.length = length
self.outputType = outputType
self.fontsize = fontsize
self.mode = mode
self.backgroundColor = backgroundColor
self.foregroundColor = foregroundColor
self.jamNum = jamNum
self.pointBorder = pointBorder
self.fonttype = fonttype
self.font = ImageFont.truetype(self.fonttype, self.fontsize)
def getPicString(self):
"""
usage: getPicString()
return: string
for : 生成给定长度的随机字符串
todo: Nothing
"""
length = self.length
chars = self.chars
selectedChars = random.sample(chars,length)
charsToStr = string.join(selectedChars,'')
return(charsToStr)
def createChecker(self):
"""
usage: createChecker()
return: [str,pic]
str:对应的字符串
pic:对应的图片
for:
todo:
"""
randStr = self.getPicString()
randStr1 = string.join([i+" " for i in randStr],"")
im = Image.new(self.mode,self.size,self.backgroundColor)
draw = ImageDraw.Draw(im)
draw.text(self.begin, randStr1, font=self.font,fill=self.foregroundColor)
self.createJam(draw)
self.createPoints(draw)
para = [1-float(random.randint(1,2))/100,
0,
0,
0,
1-float(random.randint(1,10))/100,
float(random.randint(1,2))/500,
0.001,
float(random.randint(1,2))/500
]
im = im.transform(im.size, Image.PERSPECTIVE,para)
im=im.filter(ImageFilter.EDGE_ENHANCE_MORE)
im.save("checker.jpg",self.outputType)
return([randStr,im])
def createJam(self,draw):
"""
usage: 创建干扰线
para: draw 表示画笔
return: None
for:
todo:
"""
lineNum = random.randint(self.jamNum[0],self.jamNum[1])
for i in range(lineNum):
begin = (random.randint(0,self.size[0]),random.randint(0,self.size[1]))
end = (random.randint(0,self.size[0]),random.randint(0,self.size[1]))
draw.line([begin,end],fill = (0,0,0))
def createPoints(self,draw):
"""
usage: 创建散点噪音
para: draw 表示画笔
return: None
for:
todo:
"""
for x in range(self.size[0]):
for y in range(self.size[1]):
flag = random.randint(0,self.pointBorder[0])
if flag > self.pointBorder[1]:
draw.point((x,y),fill = (0,0,0))
del flag
if name == 'main':
c=picChecker()
t=c.createChecker()
print(t)
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8