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)

即可將字符' ^_^ '轉為圖片,如下

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM