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)