Alternative for PHP GD library in python

I was looking for a search pure python modulethat has functionality equal to the PHP GD library. I need to write text in an image file. I know that the PHP GD library can do this. Does anyone know about such a module in python too.

+3
source share
2 answers

Yes: Python or PIL image library . It is used by most Python applications that must perform image processing.

+6
source

Since you are looking for "pure Python modules", PIL may not be OK. Alternatives to PIL:

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)

+1

Source: https://habr.com/ru/post/1769765/


All Articles