Pillow

来自百合仙子's Wiki
(重定向自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
使用 ImageMagickdisplay 程序显示图像

示例

缩放图片

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 模块绘制文本

绘制文本,使用不同的字体[2]

#!/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()

问题处理

截图时支持 DPI 缩放:[3][4]

from ctypes import windll
user32 = windll.user32
user32.SetProcessDPIAware()

参见

外部链接

验证码

滤镜

半透明

博客文章

参考资料