使用 Python 生成驗證碼


PIL 的一個修改版本,稱為 pillow 庫,可用於在 Python 影像庫中生成基於文字的 **驗證碼**(全自動區分計算機和人類的圖靈測試)。

驗證碼型別

驗證碼有不同的型別,其中一些如下所示。

  • 基於文字的驗證碼:提供一系列字元,並帶有扭曲的特徵和隨機噪聲,使字元識別變得困難。

  • 基於影像的驗證碼:向人類提供影像,並扭曲特徵以使計算機難以識別影像。

  • 基於音訊的驗證碼:向人類提供口語字元或剪輯的音訊錄製,他們需要將其正確輸入到系統中。

  • 行為驗證碼:使機器人難以複製/自動化。

生成基於文字的驗證碼

透過使用 **'pillow'** 庫,我們可以生成基於文字的驗證碼,它允許我們在 Python 中建立和操作影像。所包含的步驟如下。

  • 建立空白影像

  • 生成隨機驗證碼文字

  • 定義字型、文字大小和位置

  • 生成並儲存驗證碼

建立空白影像

初始化影像引數(寬度、高度和長度)(以畫素為單位)。**'Image.new('RGB', (width, height), 'white')'** 建立一個具有給定引數的空白影像,而 **'ImageDraw.Draw(image)'** 允許我們在建立的影像上繪製內容,例如文字或噪聲。

def generate_captcha(width, height, length):
    image = Image.new('RGB', (width, height), 'white')
    draw = ImageDraw.Draw(image)

生成隨機文字

從下面的示例中,**'random.choices()'** 函式生成一個隨機字元列表,而 **'.join()'** 函式將此字元列表連線成單個字串。

captcha_text = ''.join(random.choices(string.ascii_uppercase + string.digits, k=length))

計算文字大小和位置

**'draw.text size (captcha_text, font)'** 將計算驗證碼文字的寬度和高度(以畫素為單位),而變數 **'text_x'** 和 **'text_y'** 確定文字的位置。

font = ImageFont.truetype('arial.ttf', 72)
 t_width, t_height = draw.textsize(captcha_text, font)
    text_x = (width - t_width) / 2
    text_y = (height - t_height) / 2

生成並儲存驗證碼

用於 **驗證碼** 的文字儲存在 **'captcha_text'** 中,以便在使用者提交輸入時進行驗證。

  return image, captcha_text
  
# Define CAPTCHA parameters
width = 700  # Width of the CAPTCHA image
height = 350  # Height of the CAPTCHA image
length = 6   # Length of the CAPTCHA text

captcha_image, captcha_text = generate_captcha(width, height, length)
captcha_image.save('captcha.png')

示例

from PIL import Image, ImageDraw, ImageFont
import random
import string

def generate_captcha(width, height, length):
    # Create a blank image with a white background
    image = Image.new('RGB', (width, height), 'white')
    draw = ImageDraw.Draw(image)

    # Generate random CAPTCHA text
    captcha_text = ''.join(random.choices(string.ascii_uppercase + string.digits, k=length))

    # Define the font and its size
    font = ImageFont.truetype('arial.ttf', 72)

    # Calculate the text size and position it in the center
    t_width, t_height = draw.textsize(captcha_text, font)
    text_x = (width - t_width) / 2
    text_y = (height - t_height) / 2

    # Draw the text on the image
    draw.text((text_x, text_y), captcha_text, font=font, fill='black')

    # Add noise to the image
    for x in range(width):
        for y in range(height):
            if random.random() < 0.1:  # Adjust noise level
                draw.point((x, y), fill='black')

    # Return the generated CAPTCHA image and the corresponding text
    return image, captcha_text

# Define CAPTCHA parameters
width = 700  
height = 350  
length = 6   

# Generate and save the CAPTCHA image
captcha_image, captcha_text = generate_captcha(width, height, length)
captcha_image.save('captcha.png')

輸出


更新於: 2024-11-13

2K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告