Python利用PIL编写随机生成中文验证码
首先说明大部分的代码和jb51上的那差不多,只是做了一点改变。
这个是我的一个作业,不过我去网上找了之后发现大同小异。有的不满足我的要求,就比如说字体旋转怎么搞,我自己搞的有黑边,所以我去网上找,但是发现所有人代码都一样都是抄的,抄就算了,为什么不做点改进。我去jb51这个网站看的发现基本上都和这差不多,但是脚本51上的rotate(旋转)有问题,尝试解决,已解决(利用composite解决,一定要注意fff和self.image都是rgba的格式,否则会报错)。希望能帮到更多人。
还有就是利用gbk2312会生成不了某些字符。
引用:对于第55区,D7FA-D7FE的5个是没有编码的,需要在两个字节组合的范围中特意剔除一下。(源链接)
from PIL import Image,ImageDraw,ImageFont
import random
def GBK2312():
head = random.randint(0xb0, 0xf7)
body = random.randint(0xa1, 0xfe)
val = f'{head:x}{body:x}'
str = bytes.fromhex(val).decode('gb2312')
return str
class ImageChar:
def __init__(self,FontColor=(0,0,0),FontSize=20,FontPath='./simhei.ttf',size=(100,40),BgColor=(255,255,255)):
self.FontColor=FontColor
self.FontSize=FontSize
self.Fontpath=FontPath
self.size=size
self.BgColor=BgColor
self.font=ImageFont.truetype(self.Fontpath,self.FontSize)
self.image=Image.new('RGBA',self.size,self.BgColor)
def rotate(self):
self.image= self.image.rotate(random.randint(-15, 15))
im1 = Image.new("RGBA", self.size, color=self.BgColor)
self.image = Image.composite(self.image, im1,self.image)
def drawtext(self,pos,txt,fill):
draw=ImageDraw.Draw(self.image)
draw.text(pos,txt,fill,self.font)
def randRGB(self):
return (random.randint(0,200),random.randint(0,200),random.randint(0,200))
def drawpoint(self,n):
draw=ImageDraw.Draw(self.image)
for j in range(n):
draw.point((random.randint(0,100),random.randint(0,100)),self.randRGB())
def drawLine(self, n):
draw = ImageDraw.Draw(self.image)
for i in range(n):
draw.line([(random.randint(0,100),random.randint(0,100)),(random.randint(0,100),random.randint(0,100))],self.randRGB())
def randChinese(self,num):
# gap为字体间的间距
gap=5
for i in range(num):
x=self.FontSize*i+random.randint(1,gap)+gap*i
self.drawtext((x,random.randint(0,5)),GBK2312(),self.randRGB())
self.drawpoint(random.randint(30, 40))
self.drawLine(random.randint(1, 3))
self.rotate()
def save(self,path):
self.image.save(path)
image1=ImageChar()
image1.randChinese(4)
image1.save('./1.png')
结果如图