溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何Python生成隨機驗證碼

發(fā)布時間:2020-09-10 16:25:04 來源:億速云 閱讀:596 作者:Leah 欄目:編程語言

這篇文章運用簡單易懂的例子給大家介紹如何Python生成隨機驗證碼,代碼非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

驗證碼是web開發(fā)中不可缺少的元素,而python又提供了非常多的驗證碼模塊幫助大家快速生成各種驗證碼。那你知道驗證碼生成的原理嗎?所謂知其然,還要知其所以然。今天給大家介紹一下驗證碼:

演示環(huán)境

·操作系統(tǒng):windows10

·python版本:python 3.7

·代碼編輯器:pycharm 2018.2

·使用第三方模塊:pillow

驗證碼的必須元素

1.一張圖片

2.文本

3.干擾元素

    ·線條干擾

    ·小圓點干擾

熟悉pillow庫

我們既然需要使用pillow庫制作驗證碼,那么首先我們先來熟悉一下我們需要用到的方法。

1、Image.new():這個方法可以生成一張圖片,有三個參數(shù)。

    ·mode:顏色空間模式,可以是'RGBA','RGB','L'等等模式

    ·size:圖片尺寸,接收一個兩個整數(shù)的元祖

    ·color:圖片的填充顏色,可以是red,green等,也可以是rgb的三個整數(shù)的元祖。也就是背景顏色

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

上面代碼創(chuàng)建了一個億RGB為顏色空間模式,尺寸為1080*900,背景顏色為白色的圖片。

2、Image.save():保存圖片到本地

    ·fp:本地文件名

    ·format:可選參數(shù),制定文件后綴名。

from PIL import Image
captcha = Image.new('RGB', (1080, 900), (255,255,255))
# captcha.save('captcha.png')
captcha.save('captcha', format='png')

上面兩種方式保存效果是一樣的。

3、Image.show():顯示圖片,會調(diào)用電腦自帶的顯示圖片的軟件。

4、ImageFont.truetype():加載一個字體文件。生成一個字體對象。

from PIL import ImageFont
#                字體文件路徑 字體大小
font = ImageFont.truetype('simkai.ttf', 16)

5、ImageDraw.Draw():生成畫筆對象。

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

上面就創(chuàng)建了一個在captcha這張圖片上的畫筆,我們在這個圖片上畫任何東西都會使用這個畫筆對象。

6、ImageDraw.Draw().text():在圖片上繪制給定的字符

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

7、ImageDraw.Draw().line():在圖片上繪制線條

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

8、ImageDraw.Draw().point():在圖片上繪制點

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

制作我們的驗證碼我們就會使用到上面的方法。當(dāng)然,pillow肯定不止這些方法,這里我們就只列舉這些了。

制作驗證碼

1、首先我們定義一個類,初始化一些需要的參數(shù)。

import string
class Captcha():
    '''
    captcha_size: 驗證碼圖片尺寸
    font_size: 字體大小
    text_number: 驗證碼中字符個數(shù)
    line_number: 線條個數(shù)
    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

這里說一下string模塊。

·string.ascii_letters: 得到a-zA-Z所有字符

·string.digits: 得到0-9所有數(shù)字

2、隨機從sources獲取字符

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

random.sample()方法:從第一個參數(shù)中隨機獲取字符。獲取個數(shù)有第二個參數(shù)指定。

3、隨機獲取繪制字符的顏色

def get_font_color(self):
    font_color = (random.randint(0, 150), random.randint(0, 150), random.randint(0, 150))
    return font_color

4、隨機獲取干擾線條的顏色

def get_line_color(self):
    line_color = (random.randint(0, 250), random.randint(0, 255), random.randint(0, 250))
    return line_color

5、編寫繪制文字的方法

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

6、繪制線條的方法

def draw_line(self, draw, captcha_width, captcha_height):
    '''
    繪制線條
    :param draw: 畫筆對象 
    :param captcha_width: 驗證碼的寬度 
    :param captcha_height: 驗證碼的高度
    :return: 
    '''
    # 隨機獲取開始位置的坐標(biāo)
    begin = (random.randint(0,captcha_width/2), random.randint(0, captcha_height))
    # 隨機獲取結(jié)束位置的坐標(biāo)
    end = (random.randint(captcha_width/2,captcha_width), random.randint(0, captcha_height))
    draw.line([begin, end], fill=self.get_line_color())

7、繪制小圓點

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

8、制作驗證碼

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

這樣,我們就生成了我們的圖片驗證碼了,效果圖:

如何Python生成隨機驗證碼

關(guān)于如何Python生成隨機驗證碼就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI