因为博主最近稍微研究了一下微信跳一跳辅助程序,从而认识了PIL这么个东东,然后就有了本文
在微信跳一跳中Pillow主要用法:
from PIL import Image
im = Image.open('./autojump.png')
Image.open('./autojump.png').load()
成绩只是附带结果,探究真理最重要!
Pillow is the “friendly” PIL fork by Alex Clark and Contributors. PIL is the Python Imaging Library by Fredrik Lundh and Contributors.
Why a fork?
PIL is not setuptools compatible.
Port existing PIL-based code to Pillow
Pillow is a functional drop-in replacement for the Python Imaging Library. To run your existing PIL-compatible code with Pillow, it needs to be modified to import the Imaging module from the PIL namespace instead of the global namespace. I.e. change:
import Image
to:
from PIL import Image
Note
If your code imports from _imaging, it will no longer work.
The preferred, future proof method of importing the private _imaging module is:
from PIL import Image
_imaging = Image.core
Image类
Pillow中最重要的类就是Image,该类存在于同名的模块中。可以通过以下几种方式实例化:从文件中读取图片,处理其他图片得到,或者直接创建一个图片。
使用Image模块中的open函数打开一张图片:
>>> from PIL import Image
>>> img = Image.open('./autojump.png')
如果打开成功,返回一个Image对象,可以通过对象属性检查文件内容
>>> from __future__ import print_function
>>> print(img.format,img.size,img.mode)
PNG (1440, 2560) RGBA
format属性定义了图像的格式,如果图像不是从文件打开的,那么该属性值为None;size属性是一个tuple,表示图像的宽和高(单位为像素);mode属性为表示图像的模式,常用的模式为:L为灰度图,RGB为真彩色,CMYK为pre-press图像。
如果文件不能打开,则抛出IOError异常。
当有一个Image对象时,可以用Image类的各个方法进行处理和操作图像,例如显示图片:
>>> img.show()
ps:标准版本的show()方法不是很有效率,因为它先将图像保存为一个临时文件,然后使用xv进行显示。如果没有安装xv,该函数甚至不能工作。但是该方法非常便于debug和test。(windows中应该调用默认图片查看器打开)
读写图片
Pillow库支持相当多的图片格式。直接使用Image模块中的open()函数读取图片,而不必先处理图片的格式,Pillow库自动根据文件决定格式。
Image模块中的save()函数可以保存图片,除非你指定文件格式,那么文件名中的扩展名用来指定文件格式。
图片转成jpg格式
from __future__ import print_function
import os, sys
from PIL import Image
for infile in sys.argv[1:]:
f, e = os.path.splitext(infile)
outfile = f + ".jpg"
if