前言
在Python2中,PIL(Python Imaging Library)是一个非常好用的图像处理库,但PIL不支持Python3,所以有人(Alex Clark和Contributors)提供了Pillow,可以在Python3中使用。
一、安装pillow库:
pip install pillow
Pillow库安装成功后,导包时要用PIL来导入,而不能用pillow或Pillow。
import PIL
from PIL import Image
最常用的就是Image类,pillow库中的其他很多模块都是在Image的基础上对图像做进一步的处理。
二、打开一张图片:
from PIL import Image
image = Image.open("test.png")
image.show()
三、创建一张图片:
from PIL import Image
image = Image.new('RGB', (160, 90), (0, 0, 255))
image.show()
new(mode, size, color=0)
: 创建一张图片(画布),用于绘图,是Image模块中的函数。有3个参数。
mode, 图片的模式,如“RGB”(red,green,blue三原色的缩写,真彩图像)、“L”(灰度,黑白图像)等。
size
, 图片的尺寸。是一个长度为2的元组(width, height),表示的是像素大小。
color
, 图片的颜色,默认值为0表示黑色。可以传入长度为3的元组表示颜色,也可以传入颜色的十六进制,在版本1.1.4后,还可以直接传入颜色的英文单词,如上面代码中的(0, 0, 255)可以换成‘#0000FF’或‘blue’,都是表示蓝色。
四、Image模块常用的属性:
from PIL import Image
image = Image.open("text_effect.png")
print('width: ', image.width)
print('height: ', image.height)
print('size: ', image.size)
print('mode: ', image.mode)
print('format: ', image.format)
# print('category: ', image.category)
print('readonly: ', image.readonly)
print('info: ', image.info)
width
属性表示图片的像素宽度,height属性表示图片的像素高度,width和height组成了size属性,size是一个元组。
mode
属性表示图片的模式,如RGBA,RGB,P,L等。
图片的模式可以参考:
https://pillow.readthedocs.io/en/latest/handbook/concepts.html#concept-modes
format
属性表示图片的格式,格式一般与图片的后缀扩展名相关。category属性表示图片的的类别。
readonly
属性表述图片是否为只读,值为1或0,表示的是布尔值。
info
属性表示图片的信息,是一个字典。