Add Text to Image with Php and Python

| By Webner

How to add Text to Image with Php and Python

Step 1: Call the python file from PHP with the following arguments.
$ filePathForPython: Specify the location of the python file.
$imageName: Dynamic name of the image.
$ imageText: Text to be written on the image.
$ badgeFilepath: Image on which text is to be written.
$ FontFilepath: Location of the font file.
$badgeImageName: New file name that is a combination of text and specified image.
$implodestring : This argument is used to handle a large text. To adjust the text after 28 characters in the next line and so on.

Step 2: Call the python file from php with above arguements.
exec(“python $filePathForPython $imageName \”$imageText\” \”$badgeFilepath\” \”$FontFilepath\” \”$implodestring\” 2>&1″, $output);

Step 3: Python code to add text on the image.

from __future__ import division
from PIL import Image, ImageFont, ImageDraw
import sys
import math
import array as arr
import json

badgeFilePath =sys.argv[3]
fontFilePath =sys.argv[4]
textArray =sys.argv[5]
if len(textArray)>28:

background ='RGBA', (235, vertical), (30,0,142))
draw = ImageDraw.Draw(background)
font = ImageFont.truetype(fontFilePath, 14)
for element in textArray:
    w, h = draw.textsize(element)
    draw.text(((222-w)/2,y_for_text), element, (255,255,255), font=font)
#draw.text((20,22), 'ddd', (255,255,255), font=font)
qr =
width, height = qr.size

#qr.paste(background, (11, height))
width, height = qr.size"demotext.png")

images = map(, [badgeFilePath, 'demotext.png'])
widths, heights = zip(*(i.size for i in images))
total_width = max(widths)
max_height = sum(heights)
new_im ='RGB', (total_width, max_height),(255,255,255,255))

x_offset = 0
for im in images:
  new_im.paste(im, (0,x_offset))
  x_offset += im.size[1] 
 # print(x_offset)

Output: “AWS S3 Concepts and Integration” is the text added on the above image.

Leave a Reply

Your email address will not be published. Required fields are marked *