使用Pillow库 创建简单验证码
Posted will-note
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Pillow库 创建简单验证码相关的知识,希望对你有一定的参考价值。
使用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库 创建简单验证码的主要内容,如果未能解决你的问题,请参考以下文章