Pillow处理图像模块

Pillow处理图像模块

由于PIL不支持Python3,而且更新缓慢。所以由志愿者在PIl的基础上创建了一个分支版本,命名为Pillow,Pillow目前最新支持到Python3.6,Pillow和PIL是不能共存在一个环境中的,所以如果安装有PIL的话,需要先把PIL卸载掉

安装:pip install Pillow
卸载:pip uninstall PIL

导入方式:由于是继承PIL的分支,所以Pillow的导入是这样的

import PIL
#或者是
from PIL import Image

Pillow中最为重要的几个类:

from PIL import Image, ImageDraw,ImageFont
Image       # 产生图片
ImageDraw   # 在图片上写字
ImageFont   # 控制图片上字体的样式

使用方法:

产生图片:
    img_obj = Image.new('RGB',(350,35),'red')       
   
产生针对该图片的画笔对象:
    img_draw = ImageDraw.Draw(img_obj)
    
产生一个字体样式对象:
    img_font = ImageFont.truetype(r'static\font\333.ttf',35)
    
产生的图片文字等处理好之后要先存一下,再拿出来发送给前端:存的方式
    1.文件操作(麻烦,不推荐)
    2.使用内存管理器

随机验证码图片:

import random
def get_random():
    return random.randint(0,255),random.randint(0,255),random.randint(0,255)  # 返回的是元组

def get_code(request):
    img_obj = Image.new('RGB',(350,35),get_random())        # 1.产生图片对象
    img_draw = ImageDraw.Draw(img_obj)                      #2.产生该图片的画笔对象
    img_font = ImageFont.truetype(r'static\font\333.ttf',35) #3.产生字体对象,参数:字体文件路径
    
    io_obj = BytesIO()  # 4.产生缓存对象
    
    
    code = ''
    for i in range(5):
        upper_str = chr(random.randint(65,90))
        lower_str = chr(random.randint(97,122))
        random_int = str(random.randint(0,9))
        # 随机取上面的一个
        temp_str = random.choice([upper_str,lower_str,random_int])
        # 写到图片上
        img_draw.text((45+i*60,-2),temp_str,get_random(),font=img_font)
        # 存储产生的随机验证码
        code += temp_str
    print(code)
    img_obj.save(io_obj,'png')   #  保存在内存中
    # 将产生的随机验证码存储到session中  以便于后面的验证码校验
    request.session['code'] = code
    return HttpResponse(io_obj.getvalue())  

内存读写数据 BytesIO,StringIO

from io import BytesIO,StringIO

BytesIO     能够临时帮你保存数据   获取时,以二进制的方式返回给你
StringIO    能够临时帮你保存数据  获取时, 以字符串的方式返回给你
    
    
getvalue()方法用于获得写入后的str。

猜你喜欢

转载自www.cnblogs.com/guyouyin123/p/12198158.html
今日推荐