python application learning (two)-PIL generates verification code


Preface

As an example, the website has set a verification code to prevent malicious operations such as malicious registration and posting. The principle is to generate a picture from a string of randomly generated numbers or letters, and add an interference element to the picture. This article introduces the use of python to generate a verification code, in which the code is annotated and answers to relevant knowledge

Complete the goal:
  generate the verification code as shown in the figure
Insert picture description here


1. Preparation

1. The python environment

2, related to the python library needs pip install 包名to install

pip install pillow

Two, code writing

1. Introduce the library

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

2. Configure initialization parameters

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

3. Generate a random string

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)) 

4. Generate interference lines and points

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)

5. Function to generate verification code

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)

6. Call

if __name__ == "__main__":
    get_code()

7. Complete code

# coding = utf-8
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)      #生成26个英文字母
    #print(source)
    for index in range(0,10):
        source.append(str(index))            #给刚刚的列表里添加进0-9十个数字
    return ''.join(random.sample(source,1))  #返回source中的一个随机数

#用来生成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()

At last

For other python application examples, see: https://blog.csdn.net/weixin_45386875/article/details/113766276

Guess you like

Origin blog.csdn.net/weixin_45386875/article/details/113774038