Djaingo 随机生成验证码(PIL)

基础: https://www.cnblogs.com/wupeiqi/articles/5812291.html

实例: https://www.cnblogs.com/6324TV/p/8811249.html

一、安装PIL模块

pip install pillow

二、调用PIL的类

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
from PIL import ImageFilter

三、常用方法

1、创建空白图片

img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255))
from PIL import Image
img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255))
 
# 在图片查看器中打开
# img.show() 
 
# 保存在本地
with open('code.png','wb') as f:
    img.save(f,format='png')

2、创建画笔,用于在图片上画任意内容

draw = ImageDraw.Draw(img, mode='RGB')

3、特殊字体文字

img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255))
draw = ImageDraw.Draw(img, mode='RGB')
# 第一个参数:表示字体文件路径
# 第二个参数:表示字体大小
font = ImageFont.truetype("kumo.ttf", 28)
# 第一个参数:表示起始坐标
# 第二个参数:表示写入内容
# 第三个参数:表示颜色
# 第四个参数:表示字体
draw.text([0, 0], 'python', fill="red", font=font)

四、储存位置

# 注意 这里的check_code()是一个函数,第一个返回值是图片,第二个是内容
# 1.直接打开
img,code = check_code()
img.show()

# 2. 写入文件
img,code = check_code()
with open('code.png','wb') as f:
    img.save(f,format='png')

# 3. 写入内存(Python3)
from io import BytesIO
stream = BytesIO()
img.save(stream, 'png')
stream.getvalue()

# 4. 写入内存(Python2)
import StringIO
stream = StringIO.StringIO()
img.save(stream, 'png')
stream.getvalue()

五、例子

生成图片颜色随机的验证码(大写字母、小写字母,数字),含噪点和噪线

# 获取验证码图片
def get_valid_img(request):
    from PIL import Image, ImageDraw, ImageFont
    import random

    # 获取随机的颜色
    def get_random_color():
        return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)

    # 随机获取大写字母、小写字母、数字
    def get_random_str():
        rand_num = str(random.randint(0, 9))    # 注意:int->str
        rand_low_alpha = chr(random.randint(97, 122))
        rand_upper_alpha = chr(random.randint(65, 90))
        rand_char = random.choice([rand_num, rand_low_alpha, rand_upper_alpha])
        return rand_char

    # 创建图片对象 模式、大下、颜色
    img_obj = Image.new(mode='RGB',
                        size=(220, 35),
                        color=get_random_color()
                        )
    # 创建画笔
    draw_obj = ImageDraw.Draw(img_obj)
    # 创建字体对象,字体文件路径,字体大小
    font_obj = ImageFont.truetype("static/font/kumo.ttf", 28)
    # 存储随机生成的str
    temp_list = []
    for i in range(5):
        # 循环5次,获取5个随机字符串
        random_char = get_random_str()
        temp_list.append(random_char)
        # 在图片上一次写入得到的随机字符串,参数是:定位,字符串,颜色,字体,定位根据图片的大下绝定
        draw_obj.text((20+40*i, 0), random_char, get_random_color(), font=font_obj)
    # 验证码
    vail_code = "".join(temp_list)
    print(vail_code)    # 打印随机字符串
    #   将验证码存在Session中
    request.session['vail_code'] = vail_code
    # 噪点噪线, 防止越界
    width = 220
    height = 35
    # 划线
    for i in range(5):
        x1 = random.randint(0, width)
        x2 = random.randint(0, width)
        y1 = random.randint(0, height)
        y2 = random.randint(0, height)
        draw_obj.line((x1, y1, x2, y2), fill=get_random_color())

    # 画点 40 是根据随机字符串的定位,及图片的宽度
    for i in range(40):
        draw_obj.point([random.randint(0, width), random.randint(0, height)], fill=get_random_color())
        x = random.randint(0, width)
        y = random.randint(0, height)
        draw_obj.arc((x, y, x + 4, y + 4), 0, 90, fill=get_random_color())
    # 写入内存
    from io import BytesIO
    io_obj = BytesIO()
    # 将生成的图片数据保存在io对象中
    img_obj.save(io_obj, "png")
    # 从io对象里面取上一步保存的数据
    data = io_obj.getvalue()
    return HttpResponse(data)
原文地址:https://www.cnblogs.com/wt7018/p/11312501.html