@TOC
PIL生成不同难度的验证码
今天开始要学搞搞验证码,先一点点入手,先从自动生成验证码开始哈哈,直接上代码,前面的会有很全的注释,后面就不写了
首先
def getRandomColor():
# 获取一个随机颜色(r,g,b)格式的
c1 = random.randint(0, 255)
c2 = random.randint(0, 255)
c3 = random.randint(0, 255)
return (c1, c2, c3)
def getRandomStr():
# 获取一个随机字符串 颜色随机
random_num = str(random.randint(0, 9))
random_low_alpha = chr(random.randint(97, 122))
random_upper_alpha = chr(random.randint(65, 90))
random_char = random.choice([random_num, random_low_alpha, random_upper_alpha])
return random_char
难度1:数字验证码 随机颜色
def getCaptcha_1():
# 获取数字验证码 随机颜色
# 获取一个Image对象,参数分别市RBG模式 宽150 高30 随机颜色
captcha = Image.new('RGB', (150, 30), getRandomColor())
draw = ImageDraw.Draw(captcha)
# 获取一个font字体对象参数市ttf的字体文件的目录以及字体的大小
font = ImageFont.truetype("arial.ttf", size=32)
# 在图片上写东西,参数是:定位,字符串,颜色,字体
draw.text((20, 0), str(random.randint(0, 9)), getRandomColor(), font=font)
return captcha
难度2: 固定字符串,随机颜色
你说这个是难度一也无所谓啦
def getCaptcha_2():
# 固定字符串 随机颜色
# 获取一个Image对象,参数分别市RBG模式 宽150 高30 随机颜色
captcha = Image.new('RGB', (150, 30), getRandomColor())
# 获取一个画笔对象,将图片传过去
draw = ImageDraw.Draw(captcha)
# 获取一个font字体对象参数市ttf的字体文件的目录以及字体的大小
font = ImageFont.truetype("arial.ttf", size=32)
# 在图片上写东西,参数是:定位,字符串,颜色,字体
draw.text((20, 0), 'abcd', getRandomColor(), font=font)
# captcha.save(open('test.png', 'wb'), 'png')
# captcha.show()
return captcha
难度3:随机字符串 随机颜色
def getCaptcha_3():
# 随机字符串 随机颜色
captcha = Image.new('RGB', (150, 30), getRandomColor())
draw = ImageDraw.Draw(captcha)
font = ImageFont.truetype("arial.ttf", size=32)
for i in range(4):
# 循环4次 获得4个随机字符串
random_char = getRandomStr()
# 在图片上一次写入得到的随机字符串, 参数是定位 字符串 颜色 字体
draw.text((10+i*30, 0), random_char, getRandomColor(), font=font)
# captcha.save(open('test.png', 'wb'), 'png)
# captcha.show()
return captcha
难度4:带噪点的验证码噪线的验证码
def getCaptcha_4():
# 带有噪点的验证码图片
captcha = Image.new('RGB', (150, 30), getRandomColor())
draw = ImageDraw.Draw(captcha)
font = ImageFont.truetype("arial.ttf", size=32)
for i in range(4):
random_char = getRandomStr()
draw.text((10+i*30, 0), random_char, getRandomColor(), font=font)
# 噪点噪线
width = 150
height = 30
# 划线
for i in range(2):
x1 = random.randint(0, width)
x2 = random.randint(0, width)
y1 = random.randint(0, height)
y2 = random.randint(0, height)
draw.line((x1, y1, x2, y2), fill=getRandomColor())
# 划点
for i in range(15):
draw.point([random.randint(0, width), random.randint(0, height)], fill=getRandomColor())
x = random.randint(0, width)
y = random.randint(0, height)
draw.arc((x, y, x+4, y+4), 0, 90, fill=getRandomColor())
# captcha.save(open('test.png', 'wb'), 'png')
# captcha.show()
return captcha