用Python寫一個自動生成簡單驗證碼圖片的程序

框架:PIL,Django

效果:

在這裏插入圖片描述

源碼:

from PIL import Image, ImageDraw, ImageFont  # 引入繪圖模塊
import random  # 引入隨機函數模塊
from django.http import HttpResponse  # 引入HttpResponse模塊,返回響應
from io import BytesIO  # 在內存中創建


def get_random_color():
    color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
    return color


def verification_code(request):
    # 1.1 定義變量,寬,高,背景顏色
    width = 200
    height = 50
    background_color = get_random_color()
    # 1.2 創建畫布對象
    image = Image.new('RGB', (width, height), background_color)
    # 1.3 創建畫筆對象
    draw = ImageDraw.Draw(image)
    # 1.4 調用畫筆的point()函數繪製噪點
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        draw.point(xy, fill=get_random_color())
    # 1.5 調用畫筆的line()函數製造線
    for i in range(0, 10):
        xy_start = (random.randrange(0, width), random.randrange(0, height))
        xy_end = (random.randrange(0, width), random.randrange(0, height))
        draw.line((xy_start, xy_end), fill=get_random_color())

    # 2 用draw.text書寫文字
    rand_python = ''
    for i in range(4):
        random_number = str(random.randint(0, 9))
        random_lower_letter = chr(random.randint(97, 122))
        random_upper_letter = chr(random.randint(65, 90))
        rand_python += random.choice([random_number, random_lower_letter, random_upper_letter,])
        color = get_random_color()
        text_color = [0, 0, 0]
        #
        for j in range(2):
            if color[j]-background_color[j] <= 30:
                text_color[j] = 255-color[j]
            else:
                text_color[j] = color[j]
        draw.text((i * (width/4) + 10, 2),
                  rand_python[i],
                  tuple(text_color),
                  font=ImageFont.truetype(r'C:\Windows\Fonts\BRADHITC.TTF', 40),
                  align='center')

    # 3 釋放畫筆
    del draw
    # 存入session,用於做進一步的驗證
    request.session['verification_code'] = rand_python
    # 內存文件操作
    buf = BytesIO()
    # 將圖片保存在內存中,文件類型爲png
    image.save(buf, 'png')
    # 將內存中的圖片數據返回給客戶端,MIME類型爲圖片png
    return HttpResponse(buf.getvalue(), 'image/png')


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章