Develop a must-learn verification code and teach you to write a verification code from scratch

insert image description here

This Monday, I wrote a "2000-word advice for those who want to learn Python. It is recommended to collect it and read it carefully! "Teach you how to learn python quickly.

One of them talks about why we should not be obsessed with the invocation of frameworks and modules, but should build the wheels ourselves. Then make one for you today.

Verification code is an indispensable element in web development, and python provides a lot of verification code modules to help you quickly generate various verification codes.

Do you know how the verification code is generated? The so-called know the truth, but also know the reason. During an interview, the interviewer will not praise you for your familiarity with the framework.

Then today Xiaopang will take everyone to open the verification code layer by layer to see the little mysteries-<-

demo environment

  • Operating system: windows10
  • python version: python 3.7
  • Code editor: pycharm 2018.2
  • Use third-party modules: pillow

Required elements of captcha

  1. a picture
  2. text
  3. Interfering elements
    • line interference
    • Dot Interference

Get familiar with the pillow library

Since we need to use the pillow library to make verification codes, first let's familiarize ourselves with the methods we need to use.

  1. Image.new(): This method can generate an image and has three parameters.
    • mode: color space mode, can be 'RGBA','RGB','L'etc. mode
    • size: image size, receives a tuple of two integers
    • color: The fill color of the picture, which can be red,greenequal, or the tuple of three integers of rgb. the background color
from PIL import Image

captcha = Image.new('RGB', (1080, 900), (255,255,255))

The above code creates a picture with 100 million RGB as the color space mode, the size is 1080*900, and the background color is white.

  1. Image.save(): save the image locally
    • fp: local file name
    • format: optional parameter, specify the file extension name.
from PIL import Image

captcha = Image.new('RGB', (1080, 900), (255,255,255))

# captcha.save('captcha.png')
captcha.save('captcha', format='png')

The above two methods save the effect is the same.

  1. Image.show(): To display the picture, it will call the software that comes with the computer to display the picture.

  2. ImageFont.truetype(): Load a font file. Generate a font object.

from PIL import ImageFont
#                        字体文件路径 字体大小
font = ImageFont.truetype('simkai.ttf', 16)
  1. ImageDraw.Draw(): Generates a brush object.
from PIL import Image, ImageDraw

captcha = Image.new('RGB', (1080, 900), 'red')
draw = ImageDraw.Draw(captcha)

The above creates a brush on the captcha image. We will use this brush object to draw anything on this image.

  1. ImageDraw.Draw().text(): draws the given character on the picture
from PIL import Image, ImageDraw, ImageFont

captcha = Image.new('RGB', (1080, 900), 'red')
font = ImageFont.truetype('simkai.ttf', 16)
draw = ImageDraw.Draw(captcha)

#      字符绘制位置  绘制的字符    制定字体      字符颜色
draw.text((0,0), 'hello world', font=font, fill='black')
  1. ImageDraw.Draw().line(): draw lines on the picture
from PIL import Image, ImageDraw, ImageFont

captcha = Image.new('RGB', (1080, 900), 'red')
draw = ImageDraw.Draw(captcha)

#         线条起点  线条终点
draw.line([(0,0),(1080,900)], fill='black')
  1. ImageDraw.Draw().point(): draw points on the image
from PIL import Image, ImageDraw, ImageFont

captcha = Image.new('RGB', (1080, 900), 'red')
font = ImageFont.truetype('simkai.ttf', 16)
draw = ImageDraw.Draw(captcha)

#           点的位置      颜色
draw.point((500,500), fill='black')

We will use the above method to make our verification code. Of course, pillow is definitely more than these methods, here we only list them.

Create verification code

  1. First we define a class and initialize some required parameters.

import string

class Captcha():
    '''
    captcha_size: 验证码图片尺寸
    font_size: 字体大小
    text_number: 验证码中字符个数
    line_number: 线条个数
    background_color: 验证码的背景颜色
    sources: 取样字符集。验证码中的字符就是随机从这个里面选取的
    save_format: 验证码保存格式
    '''
    def __init__(self, captcha_size=(150,100), font_size=30,text_number=4, line_number=4, background_color=(255, 255, 255), sources=None, save_format='png'):
        self.text_number = text_number
        self.line_number = line_number
        self.captcha_size = captcha_size
        self.background_color = background_color
        self.font_size = font_size
        self.format = save_format
        if sources:
            self.sources = sources
        else:
            self.sources = string.ascii_letters + string.digits

Let's talk about the string module here.

  • string.ascii_letters: get all characters a-zA-Z
  • string.digits: get all digits 0-9
  1. Get random characters from sources
import random

def get_text(self):
    text = random.sample(self.sources,k=self.text_number)
    return ''.join(text)

random.sample() method: get random characters from the first parameter. The number of acquisitions is specified by the second parameter.

  1. Randomly get the color of the drawn character

def get_font_color(self):
    font_color = (random.randint(0, 150), random.randint(0, 150), random.randint(0, 150))
    return font_color
  1. Randomly get the color of interference lines
def get_line_color(self):
    line_color = (random.randint(0, 250), random.randint(0, 255), random.randint(0, 250))
    return line_color
  1. How to write drawn text
def draw_text(self,draw, text, font, captcha_width, captcha_height, spacing=20):
    '''
    在图片上绘制传入的字符
    :param draw: 画笔对象
    :param text: 绘制的所有字符
    :param font: 字体对象
    :param captcha_width: 验证码的宽度 
    :param captcha_height: 验证码的高度
    :param spacing: 每个字符的间隙
    :return: 
    '''
    # 得到这一窜字符的高度和宽度
    text_width, text_height = font.getsize(text)
    # 得到每个字体的大概宽度
    every_value_width = int(text_width / 4)

    # 这一窜字符的总长度
    text_length = len(text)
    # 每两个字符之间拥有间隙,获取总的间隙
    total_spacing = (text_length-1) * spacing

    if total_spacing + text_width >= captcha_width:
        raise ValueError("字体加中间空隙超过图片宽度!")
    
    # 获取第一个字符绘制位置
    start_width = int( (captcha_width - text_width - total_spacing) / 2 )
    start_height = int( (captcha_height - text_height) / 2 )

    # 依次绘制每个字符
    for value in text:
        position = start_width, start_height
        print(position)
        # 绘制text
        draw.text(position, value, font=font, fill=self.get_font_color())
        # 改变下一个字符的开始绘制位置
        start_width = start_width + every_value_width + spacing
  1. how to draw lines
def draw_line(self, draw, captcha_width, captcha_height):
    '''
    绘制线条
    :param draw: 画笔对象 
    :param captcha_width: 验证码的宽度 
    :param captcha_height: 验证码的高度
    :return: 
    '''
    # 随机获取开始位置的坐标
    begin = (random.randint(0,captcha_width/2), random.randint(0, captcha_height))
    # 随机获取结束位置的坐标
    end = (random.randint(captcha_width/2,captcha_width), random.randint(0, captcha_height))
    draw.line([begin, end], fill=self.get_line_color())
  1. draw small dots
def draw_point(self, draw, point_chance, width, height):
    '''
    绘制小圆点
    :param draw: 画笔对象
    :param point_chance: 绘制小圆点的几率 概率为 point_chance/100
    :param width: 验证码宽度
    :param height: 验证码高度
    :return:
    '''
    # 按照概率随机绘制小圆点
    for w in range(width):
        for h in range(height):
            tmp = random.randint(0, 100)
            if tmp < point_chance:
                draw.point((w, h), fill=self.get_line_color())
  1. Create verification code
def make_captcha(self):
    # 获取验证码的宽度, 高度
    width, height = self.captcha_size
    # 生成一张图片
    captcha = Image.new('RGB',self.captcha_size,self.background_color)
    # 获取字体对象
    font = ImageFont.truetype('simkai.ttf',self.font_size)
    # 获取画笔对象
    draw = ImageDraw.Draw(captcha)
    # 得到绘制的字符
    text = self.get_text(

    # 绘制字符
    self.draw_text(draw, text, font, width, height)

    # 绘制线条
    for i in range(self.line_number):
        self.draw_line(draw, width, height)

    # 绘制小圆点 10是概率 10/100, 10%的概率
    self.draw_point(draw,10,width,height)

    # 保存图片
    captcha.save('captcha',format=self.format)
    # 显示图片
    captcha.show()

In this way, we have generated our image verification code, renderings.

insert image description here

The code is all uploaded to Github: https://github.com/MiracleYoung/You-are-Pythonista/tree/master/PythonExercise/App/captcha_project

Follow the official account " Python Column ", and reply to " Machine Learning E-Books " in the background to get 100 free machine learning-related e-books~

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324203024&siteId=291194637