linux(pillow 模块 生成随机验证码)

mac2024-06-06  38

from random import randint import PIL #导入pillow模块 from PIL import Image, ImageDraw, ImageFont #图形验证码 class VerifyCode(): def __init__(self,width =100,height =40,size =4): self.width = width self.height = height self.size = size def draw(self): #画布 im = Image.new('RGB',(self.width, self.height),self.__randcolor(150,250)) self.pen = ImageDraw.Draw(im) #产生随机验证码 self.code = self.__rand_string() self.__draw_string() #干扰点 self.__draw_points() #干扰线 self.__draw_line() #把验证码画在画布 im.save('yzm.png') def __draw_points(self): for i in range(200): self.pen.point((randint(1,self.width-1),randint(1,self.height-1)),self.__randcolor(10,80)) def __randcolor(self,low,high): return randint(low,high),randint(low,high),randint(low,high) def __rand_string(self): res = '' for i in range(self.size): res += str(randint(0,9)) return res def __draw_string(self): font1 = ImageFont.truetype('SIMLI.TTF', size= 20, encoding='utf-8') for i in range(self.size): x = 10 + i *((self.width - 10) // self.size) y = randint(5,15) self.pen.text((x, y),self.code[i],font = font1,fill=self.__randcolor(50,100)) def __draw_line(self): for i in range(5): x1 = randint(1,self.width-1) x2 = randint(1,self.width-1) y1 = randint(1,self.height-1) y2 = randint(1,self.height-1) self.pen.line([(x1,y1),(x2,y2)], width=1,fill=self.__randcolor(30,100)) if __name__ == '__main__': vc =VerifyCode() vc.draw()
最新回复(0)