问题
I was searching searching for a pure python module
which has functionality equalent to PHP GD library. I need to write text on a image file. I know PHP GD library can do that. Does any one know about such module in python too.
回答1:
Yes: the Python Imaging Library or PIL. It's used by most Python apps which need to do image processing.
回答2:
Since you're looking for "pure Python modules", PIL might not be OK. Alternatives to PIL:
- mahotas. It's not pure, but it only depends on numpy, which is pretty standard.
- FreeImagePy, a ctypes wrapper for FreeImage
You can also use GD directly from Python using ctypes:
Python 3/Python 2 (also runs in 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()
Source: http://www.langarson.com.au/code/testPixelOps/testPixelOps.py (Python 2)
来源:https://stackoverflow.com/questions/3943457/alternative-for-php-gd-library-in-python