驗證碼圖片


pillow模塊

驗證碼圖片需要隨機生成一張圖片,而pillow模塊就是用來生成圖片的,它可在上面生成背景圖片,然后在背景圖片上寫字、畫線條、畫點、畫圓圈等。利用此模塊可隨機生成一個帶有5個字符串,有一些干擾點線的圖片作為驗證;還需要一個BytesIO模塊,類似於文件句柄,只不過這是內存級別,用完即刪除

安裝

pip install pillow

例子

在Django視圖函數中生成驗證碼,並且把且圖片返回給客戶端

視圖函數
def get_valid_img(request):
    height = 30
    width = 120
    # 圖片大小
    from PIL import Image, ImageDraw, ImageFont  # 導入圖像、畫筆、字體模塊
    from io import BytesIO  # 導入模塊,相對於句柄,但它保存在內存中
    f = BytesIO()
    import random

    def rnd_color():
        return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)

    img = Image.new(mode='RGB', size=(120, 30), color=rnd_color())
    # 生成一張背景圖片
    draw = ImageDraw.Draw(img, mode='RGB')
    # 定義了畫在img上的畫筆
    font = ImageFont.truetype('blog/static/dist/fonts/kumo.ttf', 28)
    # 定義了一個28號的kumo字體
    # 隨機生成驗證碼
    for i in range(5):
        code = random.choice([str(random.randint(0, 9)), chr(random.randint(65, 90)),
                              chr(random.randint(97, 122))])
        # 注意random.choice傳入的是一個列表
        draw.text([i * 24, 0], code, rnd_color(), font=font)
    # 在圖片上寫字
    # 畫干擾線
    for i in range(5):
        x1 = random.randint(0, width)
        y1 = random.randint(0, height)
        x2 = random.randint(0, width)
        y2 = random.randint(0, height)
        draw.line(xy=(x1, y1, x2, y2), fill=rnd_color())
    # 畫干擾圓圈
    for i in range(20):
        x = random.randint(0, width)
        y = random.randint(0, height)
        draw.arc((x, y, x + 4, y + 4), 0, 90, fill=rnd_color())
    # 畫干擾點
    for i in range(20):
        x = random.randint(0, width)
        y = random.randint(0, height)
        draw.point((x, y), rnd_color())
    img.save(f, 'png')
    # 保存圖片
    data = f.getvalue()
    # 讀取數據
    return HttpResponse(data)
    # 返回數據

實現點擊圖片自動刷新驗證碼的功能


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM