Python之PIL生成验证码

前言

  • 准备
  • 代码编写
      • 引入库
      • 配置初始化参数
      • 生成随机字符串
      • 生成干扰线和干扰点
      • 生成验证码的函数
      • 调用
      • 完整代码

前言
网站为例防止恶意注册、发帖等恶意操作而设置了验证码,其原理是将一串随机产生的数字或字母生成一幅图片,图片上加一下干扰元素。本文介绍利用python生成一个验证码,其中代码做了注释并于相关知识的解答

完成目标:

生成如图所示的验证码

Python之PIL生成验证码_第1张图片

准备

1、python 环境
2、涉及到的 python 库需要 pip install 包名 安装

pip install pillow

代码编写

引入库

import random,string,sys,math
from PIL import Image,ImageDraw,ImageFont,ImageFilter
import os

配置初始化参数

font_path = 'C:\Windows\Fonts\simfang.ttf'   #字体位置
number = 5                                   #生成几位数的验证码
size =(100, 40)                               #生成验证码的图像大小
bgcolor = (255, 255, 255)                      #生成的背景色(白色)
draw_line = True                             #是否要加干扰线和干扰点
path = "vertification.png"                   #验证码存放位置

生成随机字符串

def random_text ():
    source = list(string.ascii_letters)  
    #print(source)
    for index in range(0, 10):
        source.append(str(index))
    return ''.join(random.sample(source, 1)) 

生成干扰线和干扰点

def random_line(drawpen,width,height):
    for i in range(random.randint(4, 8)):
        linecolor = (random.randint(0,255),random.randint(0, 255),random.randint(0, 255))  #干扰线的颜色随机
        begin = (random.randint(0, width),random.randint(0, height))  #干扰线的位置随机
        end = (random.randint(0, width),random.randint(0, height))
        drawpen.line([begin, end], fill = linecolor)

def random_point(drawpen,width,height):
    for i in range(20):
        linecolor = (random.randint(0,255),random.randint(0, 255),random.randint(0, 255))  #干扰点的颜色随机
        begin = (random.randint(0, width),random.randint(0, height))   #干扰点的位置随机
        end = (random.randint(0, width),random.randint(0, height))
        drawpen.point([begin, end], fill = linecolor)

生成验证码的函数

def get_code():
    x_start = 2    
    y_start = 0   
    width,height = size        #验证码的宽和高
    image = Image.new('RGBA', (width, height), bgcolor)    #创建图片
    font = ImageFont.truetype(font_path, 25)             #设置验证码的字体
    drawpen = ImageDraw.Draw(image)                     #生成画笔
    for i in range(number):
        fontcolor = (random.randint(0,255),random.randint(0, 255),random.randint(0, 255))     #验证码字体的颜色随机
        text = random_text()                                
        #font_width,font_height = font.getsize(text)
        x = x_start + i * int(width / (number))
        y = random.randint(y_start, int(height / 2))
        drawpen.text((x, y), text = text,font = font,fill = fontcolor)
        # drawpen.text(((width - font_width) / number,(height - font_height) / number),text = text,font = font,fill = fontcolor)
    if draw_line:
        random_line(drawpen,width,height)
        random_point(drawpen,width,height)
    # image = image.transform((width + 20,height + 20),Image.AFFINE,(1,-0.3,0,-0.1,1,0),Image.BILINEAR)    #创建扭曲
    # image = image.filter(ImageFilter.EDGE_ENHANCE_MORE)    #扭曲,边界加强
    image.save(path)
    os.startfile(path)

调用

if __name__ == "__main__":
    get_code()

完整代码

# -*- coding: utf-8 -*-
# @Time    : 2021/4/19 6:20 PM
# @Author  : 余少琪
# @FileName: test.py
# @email   : 1603453211@qq.com

import random
import string
import os

from PIL import Image, ImageDraw, ImageFont

# 字体位置
font_path = 'C:\Windows\Fonts\simfang.ttf'
# 生成几位数的验证码
number = 5
# 生成验证码的图像大小
size = (100, 40)
# 生成的背景色(白色)
bgcolor = (255, 255, 255)
# 是否要加干扰线和干扰点
draw_line = True
# 验证码存放的位置
path = "vertification.png"


# 用来生成一个随机字符串
def random_text():
    # 生成26个英文字母
    source = list(string.ascii_letters)
    for index in range(0, 10):
        # 给刚刚的列表里添加进0-9十个数字
        source.append(str(index))
    # 返回source中的一个随机数
    return ''.join(random.sample(source, 1))


# 用来生成4-8条干扰线
def random_line(drawpen, width, height):
    for i in range(random.randint(4, 8)):
        # 干扰线的颜色随机
        linecolor = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        # 干扰线的位置随机
        begin = (random.randint(0, width), random.randint(0, height))
        end = (random.randint(0, width), random.randint(0, height))
        drawpen.line([begin, end], fill=linecolor)


# 用来生成20个干扰点
def random_point(drawpen, width, height):
    for i in range(20):
        # 干扰点的颜色随机
        linecolor = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        # 干扰点的位置随机
        begin = (random.randint(0, width), random.randint(0, height))
        end = (random.randint(0, width), random.randint(0, height))
        drawpen.point([begin, end], fill=linecolor)


# 生成验证码的函数
def get_code():
    # 验证码的初始横轴偏移量
    x_start = 2
    # 验证码的初始纵轴偏移量
    y_start = 0
    # 验证码的宽和高
    width, height = size
    # 创建图片
    image = Image.new('RGBA', (width, height), bgcolor)
    # 设置验证码的字体
    font = ImageFont.truetype(font_path, 25)
    # 生成画笔
    drawpen = ImageDraw.Draw(image)
    for i in range(number):
        # 验证码字体的颜色随机
        fontcolor = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        # 生成一个随即验证码字母(或数字)
        text = random_text()
        # font_width,font_height = font.getsize(text)
        x = x_start + i * int(width / (number))
        y = random.randint(y_start, int(height / 2))
        drawpen.text((x, y), text=text, font=font, fill=fontcolor)
        # drawpen.text(((width - font_width) / number,(height - font_height) / number),text = text,font = font,fill = fontcolor)
    if draw_line:
        random_line(drawpen, width, height)
        random_point(drawpen, width, height)
    # image = image.transform((width + 20,height + 20),Image.AFFINE,(1,-0.3,0,-0.1,1,0),Image.BILINEAR)    #创建扭曲
    # image = image.filter(ImageFilter.EDGE_ENHANCE_MORE)    #扭曲,边界加强
    image.save(path)  # 不能写为.jpg,因为RGBA不能写为jpg格式
    os.startfile(path)  # windows 下打开文件


if __name__ == "__main__":
    get_code()

你可能感兴趣的:(Python)