python创建验证码

#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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值