2010-10-15 61 views
3

我在搜索pure python module,它的功能等同於PHP GD庫。我需要在圖像文件上寫文本。我知道PHP GD庫可以做到這一點。是否有人也知道在python這樣的模塊。Python GD GD庫的替代方案

回答

6

是:Python Imaging Library或PIL。它被大多數需要進行圖像處理的Python應用程序所使用。

+0

我已經使用了PIL來了解@Idlecool正在詢問的內容。 – nmichaels 2010-10-15 15:20:44

+0

它是一個純粹的Python模塊..我可以看到裏面的C文件.. – 2010-10-15 15:26:21

+1

不 - 它是一個編譯的C模塊。除此之外,這意味着它不適用於Jython或IronPython,但它比純Python實現要快得多。 – 2010-10-15 18:52:33

1

由於您正在尋找「純Python模塊」,因此PIL可能不正確。 PIL的替代品:

  • mahotas。這不是純粹的,但它只取決於numpy,這是非常標準的。
  • FreeImagePy,一個ctypes包裝器的FreeImage

也可以直接使用GD從使用Python ctypes的:

的Python 3/Python 2中(也運行在PyPy):

#!/bin/env python3 
import ctypes 

gd = ctypes.cdll.LoadLibrary('libgd.so.2') 
libc = ctypes.cdll.LoadLibrary('libc.so.6') 

## Setup required 'interface' to GD via ctypes 
## Determine pointer size for 32/64 bit platforms : 
pointerSize = ctypes.sizeof(ctypes.c_void_p())*8 
if pointerSize == 64: 
    pointerType = ctypes.c_int64 
else: 
    pointerType = ctypes.c_int32 

## Structure for main image pointer 
class gdImage(ctypes.Structure): 
    ''' Incomplete definition, based on the start of : http://www.boutell.com/gd/manual2.0.33.html#gdImage ''' 
    _fields_ = [ 
     ("pixels", pointerType, pointerSize), 
     ("sx", ctypes.c_int, 32), 
     ("sy", ctypes.c_int, 32), 
     ("colorsTotal", ctypes.c_int, 32), 
     ## ... more fields to be added here. 
     ] 
gdImagePtr = ctypes.POINTER(gdImage) 
gd.gdImageCreateTrueColor.restype = gdImagePtr 

def gdSave(img, filename): 
    ''' Simple method to save a gd image, and destroy it. ''' 

    fp = libc.fopen(ctypes.c_char_p(filename.encode("utf-8")), "w") 
    gd.gdImagePng(img, fp) 
    gd.gdImageDestroy(img) 
    libc.fclose(fp) 

def test(size=256): 
    ## Common test parameters : 
    outputSize = (size,size) 
    colour = (100,255,50) 
    colourI = (colour[0]<<16) + (colour[1]<<8) + colour[2] ## gd Raw 

    ## Test using GD completely via ctypes : 
    img = gd.gdImageCreateTrueColor(outputSize[0], outputSize[1]) 
    for x in range(outputSize[0]): 
     for y in range(outputSize[1]): 
      gd.gdImageSetPixel(img, x, y, colourI) 
    gdSave(img, 'test.gd.gdImageSetPixel.png') 

if __name__ == "__main__": 
    test() 

來源:http://www.langarson.com.au/code/testPixelOps/testPixelOps.py(Python 2)