Python中PHP GD库的替代方案

5 投票
2 回答
4584 浏览
提问于 2025-04-16 05:33

我在找一个纯Python模块,它的功能跟PHP的GD库一样。我需要在图片上写文字。我知道PHP的GD库可以做到这一点。有没有人知道Python里有没有这样的模块呢?

2 个回答

3

因为你在找“纯Python模块”,所以PIL可能不太合适。这里有一些PIL的替代品:

  • mahotas。虽然它不是纯的,但只依赖于numpy,而numpy是个比较常用的库。
  • FreeImagePy,这是一个为FreeImage提供的ctypes封装。

你也可以直接通过ctypes在Python中使用GD:

适用于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)

7

没错,Python有一个叫做Python图像库(PIL)的东西。很多需要处理图片的Python应用都会用到它。

撰写回答