PIL生成验证码

2022-08-30  本文已影响0人  小黄不头秃
import PIL.ImageDraw as draw
import PIL.Image as image
import PIL.ImageFont as imgfont
import random
import numpy as np

font = imgfont.truetype("ARLRDBD.TTF",size=60) # 引入字体 幼圆字体

def random_chart_num():
    '''生成随机字母和数字'''
    pro = random.random()
    if pro >=0.5:
        return str(random.randint(0,9))
    else:
        return chr(random.randint(65,90))


def randchar():
    '''生成随机字母'''
    return chr(random.randint(65,90))

def generate_bgc():
    '''生成随机背景色'''
    return (random.randint(65,200),random.randint(65,200),random.randint(65,200))

def generate_fgc():
    '''生成随机前景色'''
    return (random.randint(30,100),random.randint(30,100),random.randint(30,100))

def draw_borad(w,h):
    '''生成画板'''
    img = image.new("RGB",(w,h),(255,255,255))
    return img

if __name__ == '__main__':
    width = 240
    hight = 120
    img = draw_borad(width,hight)
    img1 = draw.Draw(img)
    for x in range(width):
        for y in range(hight):
            img1.point((x,y),fill=generate_bgc())
    for i in range(4):
        img1.text((60*i+10,30),text=random_chart_num(),fill=generate_fgc(),font=font)
    img.show()



上一篇下一篇

猜你喜欢

热点阅读