from PIL import Image,ImageFont,ImageDraw,ImageFilter
import random
import string
import sys
import math

numbers=4
size=(150,60)
bgcolor=(255,255,255)
font_color=(0,0,0)
draw_line=True
line_numbers=(1,5)

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

 

def bgfontrange():
  global bgcolor
  color1=random.randint(0,255)
  color2=random.randint(0,255)
  color3=random.randint(0,255)
  bgcolor=(color1,color2,color3)

def ftfontrange():
  global font_color
  color1=random.randint(0,255)
  color2=random.randint(0,255)
  color3=random.randint(0,255)
  font_color=(color1,color2,color3)

 

 

#生成一个写字函数

def make_text():
  source=[str(x) for x in range(0,10)]
  source2=list(string.ascii_letters)
  source.extend(source2)
  return ''.join(random.sample(source,numbers))

 

#生成一个划线函数

def make_line(draw,width,height):
  begin=(random.randint(0,width),random.randint(0,height))
  end=(random.randint(0,width),random.randint(0,height))
  draw.line([begin,end],fill=font_color,width=3)

#生成验证码
def make_codepng():
  width,height=size #图片的宽度和高度
  image=Image.new(mode='RGB',size=(width,height),color=bgcolor) #创建图片
  draw=ImageDraw.Draw(image) #绘图工具
  text=make_text() #生成随机字符串
  font=ImageFont.truetype('simhei.ttf',40)
  font_width,font_height=font.getsize(text) #得到字体的宽度和高度
  draw.text(((width-font_width)/numbers,height-font_height),text,font=font,fill=font_color) #写入文字
if draw_line:
  make_line(draw,width,height)

  image=image.transform((width+40,height+30),Image.AFFINE,(1,-0.5,0,-0.2,0.9,0),Image.BILINEAR) #扭曲
  image=image.filter(ImageFilter.EDGE_ENHANCE_MORE) #处理边界
  image.save(r"D:\计算机二级\验证码"+"\\"+text+".png")
for i in range(100):
  bgfontrange()

  ftfontrange()

  make_codepng()

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄