前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python之PIL生成验证码

Python之PIL生成验证码

作者头像
全栈程序员站长
发布2022-06-29 15:20:07
4280
发布2022-06-29 15:20:07
举报
文章被收录于专栏:全栈程序员必看

前言

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

完成目标:

生成如图所示的验证码

在这里插入图片描述
在这里插入图片描述

准备

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

pip install pillow

代码编写

引入库

代码语言:javascript
复制
import random,string,sys,math
from PIL import Image,ImageDraw,ImageFont,ImageFilter
import os

配置初始化参数

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

生成随机字符串

代码语言:javascript
复制
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)) 

生成干扰线和干扰点

代码语言:javascript
复制
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)

生成验证码的函数

代码语言:javascript
复制
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)

调用

代码语言:javascript
复制
if __name__ == "__main__":
    get_code()

完整代码

代码语言:javascript
复制
# -*- 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()

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/100692.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021年5月2,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 准备
  • 代码编写
    • 引入库
      • 配置初始化参数
        • 生成随机字符串
          • 生成干扰线和干扰点
            • 生成验证码的函数
              • 调用
                • 完整代码
                相关产品与服务
                验证码
                腾讯云新一代行为验证码(Captcha),基于十道安全栅栏, 为网页、App、小程序开发者打造立体、全面的人机验证。最大程度保护注册登录、活动秒杀、点赞发帖、数据保护等各大场景下业务安全的同时,提供更精细化的用户体验。
                领券
                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档