Pillow的安装和使用

需要把一段文字转换成图片,我找到了PIL(Python Imaging Library)库,专门干这个用的。还有一个Pillow是“friendly PIL fork”,于是我选择了后者。

安装过程稍有曲折,主要是要先把它的依赖库安装就绪,再装Pillow,过程如下:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"  # 安装brew
sudo easy_install pip #安装pip
brew install libzip   # 安装libzip
ln -s /usr/local/include/freetype2 /usr/local/include/freetype   
ln -s /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers/X11 /usr/local/include/X11

sudo pip install pillow  # 安装pillow

刚开始我在没有安装libzip和freetype之前,直接安装了pillow,会报出如下错误:

/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include/tk.h:78:11: fatal error: 
      'X11/Xlib.h' file not found
#       include <X11/Xlib.h>
                ^
1 error generated.
error: command 'cc' failed with exit status 1
    font = PIL.ImageFont.truetype('Helvetical', 16)
  File "/Library/Python/2.7/site-packages/PIL/ImageFont.py", line 218, in truetype
    return FreeTypeFont(filename, size, index, encoding)
  File "/Library/Python/2.7/site-packages/PIL/ImageFont.py", line 134, in __init__
    self.font = core.getfont(file, size, index, encoding)
  File "/Library/Python/2.7/site-packages/PIL/ImageFont.py", line 34, in __getattr__
    raise ImportError("The _imagingft C module is not installed")
ImportError: The _imagingft C module is not installed
IOError: encoder zip not available

将前面的依赖库安装就绪之后,这些问题就都解决了。

写段代码如下:

import    loggingimport    PIL.Image
import    PIL.ImageDraw
import    PIL.ImageFont
        
class    Main(object):
    def text2png(self, text, fontName, fontSize, pngPath):
        font = PIL.ImageFont.truetype(fontName, fontSize)
        width, height = font.getsize(text)
        logging.debug('(width, height) = (%d, %d)' % (width, height))
        image = PIL.Image.new('RGBA', (width, height), (0, 0, 0, 0))  # 设置透明背景
        draw = PIL.ImageDraw.Draw(image)
        draw.text((0, 0), text, font = font, fill = '#000000')
        image.save(pngPath)

    def    Main(self):
        text = u' ^_^ '
        fontName = '/Library/Fonts/华文黑体.ttf'
        pngPath = 'test.png'
        self.text2png(text, fontName, 37, pngPath)

即可将字符' ^_^ '转为图片,如下

原文地址:https://www.cnblogs.com/palance/p/4809798.html