Python实现随机生成图片验证码详解
时间:2022-10-22 13:56:54|栏目:Python代码|点击: 次
使用python生成一个图片验证码,随机的,可以由于验证人机和别的啊,很方便很简单
导入模块
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()
完整代码:
#!/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()