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

filename=sys.argv[1]
imageText=sys.argv[2]
badgeFilePath =sys.argv[3]
fontFilePath =sys.argv[4]
textArray =sys.argv[5]
if len(textArray)>28:
	textArray=textArray.split('&^%*')
else:
	textArray=[textArray]

total_length=len(textArray)
vertical=int(total_length*25)
background = Image.new('RGBA', (235, vertical), (30,0,142))
draw = ImageDraw.Draw(background)
font = ImageFont.truetype(fontFilePath, 14)
y_for_text=5
for element in textArray:
    w, h = draw.textsize(element)
    draw.text(((222-w)/2,y_for_text), element, (255,255,255), font=font)
    y_for_text=y_for_text+17
#draw.text((20,22), 'ddd', (255,255,255), font=font)
qr = Image.open(badgeFilePath)
width, height = qr.size

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

background.save("demotext.png")

images = map(Image.open, [badgeFilePath, 'demotext.png'])
widths, heights = zip(*(i.size for i in images))
#print(heights)
total_width = max(widths)
max_height = sum(heights)
#print(max_height)
#print(total_width)
new_im = Image.new('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)
  #print(im.size)

new_im.save(filename)

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 *