1. 程式人生 > >使用Pillow庫 創建簡單驗證碼

使用Pillow庫 創建簡單驗證碼

tex pan tco rgba 隨機 save pat origin code

使用Pillow生成簡單的驗證碼

本想做成字體各自按隨機角度傾斜, 但沒有在Pillow中找到相關的方法

技術分享圖片

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


class GetCaptcha:
size = (100, 40)
source = tuple(string.digits + string.ascii_letters)
number = 4
background_color = (250, 250, 250)
fontsize = 25
font_path = os.path.join(os.path.dirname(__file__), ‘verdana.ttf‘)
random.seed(time.time())
fontcolor = (random.randint(0, 80), random.randint(0, 80), random.randint(0, 80))
draw_line = True
line_number = 3
line_color = (random.randint(0, 250), random.randint(0, 255), random.randint(0, 250))
draw_point = True
rotate = True

@classmethod
def image_rotate(cls, original_image):
image = original_image.rotate(random.randint(-15, 15), expand=0)
back_ground = Image.new(‘RGBA‘, cls.size,cls.background_color)
return Image.composite(image, back_ground, image)

@classmethod
def draw_text(cls):
"""return a captcha include digit and letter"""
return ‘‘.join(random.sample(cls.source, cls.number))

@classmethod
def __draw_line(cls, draw, width, height):
begin = (random.randint(0, width), random.randint(0, height))
end = (random.randint(0, width), random.randint(0, height))
draw.line([begin, end], fill=cls.line_color)

@classmethod
def __draw_point(cls, draw, point_size, width, height):
size = min(100, max(0, int(point_size)))
for w in range(width):
for h in range(height):
tmp = random.randint(0, 100)
if tmp > 100 - size: # make sure would not point too much
draw.point((w, h), fill=(150, 150, 150))


@classmethod
def draw_captcha(cls):
width, height = cls.size
image = Image.new(‘RGBA‘, (width, height), cls.background_color)
font = ImageFont.truetype(cls.font_path, cls.fontsize)
draw = ImageDraw.Draw(image)
text = cls.draw_text()
font_width, font_height = font.getsize(text)
draw.text(((width - font_width) / 2, (height - font_height) / 2), text, font=font, fill=cls.fontcolor)

if cls.draw_line:
for x in range(0, cls.line_number):
cls.__draw_line(draw, width, height)

if cls.draw_point:
cls.__draw_point(draw, 5, width, height)

return (text, cls.image_rotate(image))


if __name__ == "__main__":
captcha = GetCaptcha()
text, image = captcha.draw_captcha()
image.save(‘code.png‘, "PNG")

在Django的視圖中返回

def captcha_view(request):
text, image = GetCaptcha.draw_captcha()
output = BytesIO()
image.save(output,‘png‘)
output.seek(0)
response = HttpResponse()
response[‘content/type‘] = "image/png"
response.write(output.read())
return response

使用Pillow庫 創建簡單驗證碼