python生成验证码

import random,string,sys,math
from PIL import Image, ImageDraw, ImageFont, ImageFilter
font_path='C:\Windows\Fonts\simkai.ttf' #设置字体
number=4
size=(80,30)
bgcolor=(137,215,188)
fontcolor=(103,171,214)
linecolor=(244,109,144)
draw_line=True  #加干扰线
line_number=(1,5) #干扰线范围

#随机生成字符串
def gene_text():
    source=list(string.ascii_letters)#a-z
    for index in range(0,10):  #加入0-9
        source.append(str(index))
    return ''.join(random.sample(source,number)) #连起来 中间 没有间隔

def gene_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=linecolor)

#生成验证码
def gene_code():
    width,height=size  #宽与高
    image=Image.new('RGBA',(width,height),bgcolor)
    font=ImageFont.truetype(font_path,25)
    draw=ImageDraw.Draw(image)
    text=gene_text()
    font_width,font_height=font.getsize(text)
    draw.text(((width-font_width)/number,(height-font_height)/number),text,font=font,fill=fontcolor) #填充字符串
    if draw_line:
        gene_line(draw,width,height)
    image=image.transform((width+20,height+10), Image.AFFINE,(1,-0.3,0,-0.1,1,0),Image.BILINEAR)

    image=image.filter(ImageFilter.EDGE_ENHANCE_MORE)
    image.save("2.png")




if __name__=="__main__":
    gene_code()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值