开发者

Python实现随机生成图片验证码详解

使用python生成一个图片验证码,随机的,可以由于验证人机和别的啊,很方http://www.cppcns.com便很简单

导入模块

import random
from PIL import Image,ImageFont,ImageDraw

生成随机验证码

def rndtxt():
    txt_list = []
    # 大写字母
    txt_list.extend([i for i in range(65,90)])
    # 小写字母
    txt_list.extend([i for i in range(97,1http://www.cppcns.com23)])
    # 数字
    txt_list.extend([i for i in range(48,57)])
    return chr(txt_list[random.randint(0,len(txt_list)-1)])

作为待会生成的图片背景色和字体色

def rndbgcolor():
    # 背景颜色
    return (random.randint(64,255),random.randint(64,255),random.randint(64,255))
 
def rndtxtcolor2():
    # 字体颜色
    return (random.randint(32,127),random.randint(32,127),random.randint(32,127))

进行生成打印验证码并以图片的形式打开,不保存图片文件,仅用于一时的验证码验证

def code():
    weight = 240
    hight = 60
    image = Image.new('RGB',(weight,hight),(255,255,255))
    font = ImageFont.truetype('msyh.ttc',36)
    draw = ImageDraw.Draw(image)
 
    # 填充背景颜色
    for x in range(weight):
        for y in range(hight):
            draw.point((x,y),fill=rndbgcolor())
 
    # 生成随机验证码
    for T in range(4):
        rndtxt_2 = rndtxt()
        print(rndtxt_2)       # 打印验证码的值
        draw.text((60 * T + 10,10),rndtxt_2,font=font,fill=rndtTktXfHxtcolor2())
    image.show()

Python实现随机生成图片验证码详解

完整代码:

#!/usr/bin/env python3
import random
from PIL import Image,ImageFont,ImageDraw
 
def rndtxt():
    txt_list = []
    # 大写字母
    txt_list.extend([i for i in range(65,90)])
    # 小写字母
    txt_list.extend([i for i in range(97,123)])
    # 数字
    txt_list.extend([i for i in range(48,57)])
    return chr(txt_list[random.randint(0,len(txt_编程客栈list)-1)])
 
def rndbgcolor():
    # 背景颜色
    return (random.randint(64,255),random.randint(64,255),random.randint(64,255))
 
def rndtxtcolor2():
    # 字体颜色
    return (random.randint(32,127),random.randint(32,127),random.randint(32,127))
 
def code():
    weight = 240
    hight = 60
    image = Image.new('RGB',(weight,hight),(255,255,255))
    font = ImageFont.truetype('msyh.ttc',36)
    draw = ImageDraw.Draw(image)
 
    # 填充背景颜色
    for x in range(weight):
        for y in range(hight):
            draw.point((x,y),fill=rndbgcolor())
 
    # 生成随机验证码
  编程客栈  for T in range(4):
        rndtxt_2 = rndtxt()
        print(rndtxt_2)       # 打印验证码的值
        draw.text((60 * T + 10,10),rndtxt_2,font=font,fill=rndtxtcolor2())
    image.show()
 
code()

以上就是Python实现随机生成图片验证码详解的详细内容,更多关于Python图片验证码的资料请关注我们其它相关文章!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜