Python Imaging Library

Bugs in PIL 1.1.7

negative height on BMP files

BMP 的檔案格式中,Height 這個欄位(offset 0x16)可以是負值,用來標示讀圖時的掃瞄方向(由上而下還是由下而上)
但 height 是負值時,PIL.open 讀進來的 raw data 卻沒作翻轉處理,導致 image.show() 的圖是反的
以下是偵測順便修正的 function

import os
 
import Image
 
def fix_bmp(im, img_fn):
    """Flip a BMP image if it has a negavie height.
    """
    flip = lambda x: im.transpose(Image.FLIP_TOP_BOTTOM)
 
    ext = os.path.splitext(img_fn)[1].upper()
    if ext == '.BMP':
        OFFSET_OF_HEIGHT = 0x16
        OFFSET_OF_HEIGHT_END = OFFSET_OF_HEIGHT + 4
        with open(img_fn, 'rb') as f:
            bytes = f.read(OFFSET_OF_HEIGHT_END)
        if bytes[-1] == chr(0xFF):  # is a negative height?
            im = flip(im)
    return im
 
filename = 'test.bmp'
im = Image.open(filename)
im = fix_bmp(im, filename)

The _imagingft C module is not installed

下面這段會 raise ImportError("The _imagingft C module is not installed")

import ImageFont
 
# use a truetype font
font = ImageFont.truetype("arial.ttf", 20)

解法有二

  1. 改裝 python(x y)
  2. 改裝 這個 unoffical 的 PIL

可參考 The _imagingft C module is not installed in python 2.7

需要注意的是

  • 原本舊的 PIL 記得要砍乾淨,不然會無效
    • 先 uninstall PIL
    • 然後到 Lib\site-packages 目錄下把 PIL 的 .egg 目錄砍掉
    • 最後才執行 PIL-fork-1.1.7.win32-py2.7.exe 安裝這個 unofficial PIL 的版本

Bugs in PIL 1.1.6

ImageColor.getcolor incorrect for grayscale

PIL 的 'L' mode ,顏色值少 1 ,
以下連結有 patch 檔,可更正這個問題。
ImageColor.getcolor incorrect for grayscale

Incorrect font position

利用 ImageDraw 的 text() 畫字時,特定字型在 size 小時,會出錯。
判斷應該是 Windows 下 drawing 相關 back-end 有 bug 。

可以改用 aggdraw

import os
from PIL import Image
import aggdraw
 
fontfile = "ProFontWindows.ttf" # cour.ttf ProFontWindows.ttf
windir = os.environ.get("WINDIR")
if windir:
    fontfile = os.path.join(windir, "fonts", fontfile)
fontsize = 12
(W, H) = (100, 100)
 
#im = Image.new("L", (W, H), "Black")
#draw = aggdraw.Draw(im)
draw = aggdraw.Draw("L", (W, H), "Black")
draw.setantialias(False)
font = aggdraw.Font("White", fontfile, fontsize)
text = "A"
w, h = draw.textsize(text, font)
print w, h
draw.text((0, 0), text, font) # incorrect with ImageDraw
#draw.flush()
 
im = Image.fromstring("L", (W, H), draw.tostring()).convert("1")
 
from PIL import ImageFont, ImageDraw
font = ImageFont.truetype(fontfile, fontsize)
print font.getsize(text)
draw = ImageDraw.Draw( im )
draw.text((0,h), text, font=font, fill="White") # correct with aggdraw
del draw
im.show()
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License