1 from PIL import Image,ImageFont,ImageDraw,ImageFilter 2 import random 3 import string 4 import sys 5 import math 6 7 numbers=4 8 size=(150,60) 9 bgcolor=(255,255,255) 10 font_color=(0,0,0) 11 draw_line=True 12 line_numbers=(1,5) 13 14 15 16 def bgfontrange(): 17 global bgcolor 18 color1=random.randint(0,255) 19 color2=random.randint(0,255) 20 color3=random.randint(0,255) 21 bgcolor=(color1,color2,color3) 22 23 def ftfontrange(): 24 global font_color 25 color1=random.randint(0,255) 26 color2=random.randint(0,255) 27 color3=random.randint(0,255) 28 font_color=(color1,color2,color3) 29 30 31 32 33 34 #生成一个写字函数 35 36 def make_text(): 37 source=[str(x) for x in range(0,10)] 38 source2=list(string.ascii_letters) 39 source.extend(source2) 40 return ''.join(random.sample(source,numbers)) 41 42 43 44 #生成一个划线函数 45 46 def make_line(draw,width,height): 47 begin=(random.randint(0,width),random.randint(0,height)) 48 end=(random.randint(0,width),random.randint(0,height)) 49 draw.line([begin,end],fill=font_color,width=3) 50 51 #生成验证码 52 def make_codepng(): 53 width,height=size #图片的宽度和高度 54 image=Image.new(mode='RGB',size=(width,height),color=bgcolor) #创建图片 55 draw=ImageDraw.Draw(image) #绘图工具 56 text=make_text() #生成随机字符串 57 font=ImageFont.truetype('simhei.ttf',40) 58 font_width,font_height=font.getsize(text) #得到字体的宽度和高度 59 draw.text(((width-font_width)/numbers,height-font_height),text,font=font,fill=font_color) #写入文字 60 if draw_line: 61 make_line(draw,width,height) 62 63 image=image.transform((width+40,height+30),Image.AFFINE,(1,-0.5,0,-0.2,0.9,0),Image.BILINEAR) #扭曲 64 image=image.filter(ImageFilter.EDGE_ENHANCE_MORE) #处理边界 65 image.save(r"D:计算机二级验证码"+"\"+text+".png") 66 for i in range(100): 67 bgfontrange() 68 69 ftfontrange() 70 71 make_codepng()