#python创建验证码
import random,string,math
from PIL import Image,ImageFont,ImageDraw,ImageFilter
import matplotlib.pyplot as plt
size=(80,30)#验证码宽高
def create_text():
source=list(string.ascii_letters)
for i in range(0,10):
source.append(str(i))#加入数字
return "".join(random.sample(source,4))#返回四位
#干扰线
def disturb_line(draw,width,height):
for j in range(0,5):
begin = (random.randint(0, width), random.randint(0, height)) # 元组
end = (random.randint(0, width), random.randint(0, height))
draw.line([begin, end], fill=(255, 0, 0)) # 红色干扰线
#生成验证码
def result():
width,height=size#不需要全局
image=Image.new("RGBA",size,(255,255,255))#背景默认白色
font=ImageFont.truetype("C:\Windows\Fonts\simfang.ttf",25)#字体选择
draw=ImageDraw.Draw(image)#画笔
text=create_text()
font_w,font_h=font.getsize(text)
draw.text(((width-font_w)//4,(height-font_h)//4),text,fill=(0,0,255),font=font)
disturb_line(draw,width,height)#干扰,传入画笔类
image=image.transform((width+10,height+5),Image.AFFINE,(1,0.1,-0.1,0,1,0),Image.BILINEAR)#双线性
#第三行默认0,0,1
image=image.filter(ImageFilter.EDGE_ENHANCE_MORE)
plt.imshow(image)
plt.show()
if __name__=="__main__":
result()


317

被折叠的 条评论
为什么被折叠?



