from PIL import Image,ImageDraw,ImageFont
import random,string
class ImageCode:
def get_color(self):
red = random.randint(32,127)
green = random.randint(0,255)
blue = random.randint(60,255)
return red,green,blue
def get_code(self):
code = random.sample(string.ascii_letters+string.digits,6)
return ''.join(code)
def randon_lines(self,draw,num,width,height):
for num in range(num):
x1 = random.randint(0,width/2)
y1 = random.randint(0,width/2)
x2 = random.randint(width/2,width)
y2 = random.randint(height/2,height)
draw.line(((x1,y1),(x2,y2)),fill= self.get_color(),width=2)
def get_image(self):
code = self.get_code()
width,height = 120,60
image = Image.new('RGB',(width,height),'white')
font = ImageFont.truetype('arial.ttf', size=40)
draw = ImageDraw.Draw(image)
for i in range(4):
draw.text((5+random.randint(-3,3)+23*i,5+random.randint(-3,3)),text=code[i],fill=self.get_color(),font=font)
self.randon_lines(draw,6,width,height)
image.show()
ImageCode().get_image()
python类随机生成图片验证码
最新推荐文章于 2024-10-12 11:26:53 发布