Pillow
(重定向自PIL)
Image 对象
属性
size- 一个 tuple,表示图像大小
mode- 如 'RGBA'
方法
convert- 改变模式,返回新的
Image。模式可为RGB, RGBA, L等 load- returns a pixel access object that can be used to read and modify pixels. The access object behaves like a 2-dimensional array
resize- 调整大小
save- 保存。参数为文件名或者
(buffer, 扩展名) show- 使用 ImageMagick 的 display 程序显示图像
示例
缩放图片
from PIL import Image
img = Image.open('img.png')
new_img = img.resize((800, 600))
new_img.save('new.jpg')
使用 ImageDraw 模块画画
用来在图像上画画[1],如
from PIL import Image, ImageDraw
img = Image.open('xxx.png')
draw = ImageDraw.Draw(img)
draw.rectangle((0, 0, 30, 40))
draw.rectangle((30, 40, 100, 140), outline=(255, 0, 255))
使用 ImageFont 模块绘制文本
#!/usr/bin/env python3
from PIL import Image, ImageDraw, ImageFont
from myutils import findfont
fonts = [ ... ]
w, h = 800, 2000
image = Image.new('RGB', (w, h), 'white')
draw = ImageDraw.Draw(image)
pos = 0
w = 0
strs = '像我这样为爱痴狂,到底你会怎么想?'
for fontname in fonts:
font = ImageFont.truetype(findfont(fontname), 24)
s = '%s: %s' % (fontname, strs)
font_width, font_height = font.getsize(s)
w = max((font_width, w))
draw.text((10, pos), s, font=font, fill='black')
pos += font_height
h = pos
image = image.crop((0, 0, w+10, h))
image.save('fonts.png')
遍历字体来绘制文本
使用了 python-fontconfig 模块来过滤字体。
#!/usr/bin/env python3
from PIL import Image, ImageDraw, ImageFont
import fontconfig
string = '亮滑以角没過化骨麵廣房空'
def get_fonts():
files_checked = set()
ret = []
for f in fontconfig.query():
if f in files_checked:
continue
files_checked.add(f)
f = fontconfig.FcFont(f)
if all(f.has_char(ch) for ch in string):
ret.append((f.file, 0, f.bestname))
for i in range(1, f.count):
f = fontconfig.FcFont(f.file, index=i)
if all(f.has_char(ch) for ch in string):
ret.append((f.file, i, f.bestname))
return ret
def main():
w, h = 800, 20000
image = Image.new('RGB', (w, h), 'white')
draw = ImageDraw.Draw(image)
pos = 0
w = 0
strs = string
for fontfile, i, fontname in get_fonts():
font = ImageFont.truetype(fontfile, 24, index=i)
s = '%s: %s' % (fontname, strs)
font_width, font_height = font.getsize(s)
w = max((font_width, w))
draw.text((10, pos), s, font=font, fill='black')
pos += int(font_height * 1.5)
h = pos
image = image.crop((0, 0, w+10, h))
image.save('fonts.png')
if __name__ == '__main__':
main()
问题处理
from ctypes import windll
user32 = windll.user32
user32.SetProcessDPIAware()
参见
- Python
- Wand, 基于 ctypes 的 ImageMagick 绑定
- 图像处理算法
外部链接
- 官方网站
- Python Imaging Library Handbook
- Python 3 版下载地址
- Pillow is the "friendly" PIL fork. 支持 Python 3。
验证码
滤镜
- The ImageFilter Module
- Python图形图像处理库的介绍之ImageFilter模块(滤镜),有各种滤镜的效果展示
- 用PIL实现滤镜(一)——素描、铅笔画效果 - 残阳似血的博客, 代码