Skip to content

Instantly share code, notes, and snippets.

@navenduagarwal
Last active June 8, 2018 09:27
Show Gist options
  • Save navenduagarwal/4c76a6f8d5982bb4a24fd48787b24b47 to your computer and use it in GitHub Desktop.
Save navenduagarwal/4c76a6f8d5982bb4a24fd48787b24b47 to your computer and use it in GitHub Desktop.
To insert multi line text (custom font) in an image using python pillow library
from PIL import ImageFont, ImageDraw, Image
import textwrap
import requests
from io import BytesIO
# # load image from file
# image = Image.open("e1.jpg")
# loading image from url
image_from_url = requests.get("https://dummyimage.com/600x1000/000/fff&text=+")
image = Image.open(BytesIO(image_from_url.content)).convert('RGB')
draw = ImageDraw.Draw(image)
startHeight = 820 # fix height, can be taken as an input
color = "#ffffff"
text1 = "Text1"
text2 = "Text2"
# use a truetype font
font1 = ImageFont.truetype("regular.ttf", 40)
font2 = ImageFont.truetype("regular.ttf", 40)
# get image size to align text
iw, ih = image.size
print('{},{}'.format(iw,ih))
# get font size
w1, h1 = font1.getsize(text1)
w2, h2 = font2.getsize(text2)
print('{},{}'.format(w1,h1))
print('{},{}'.format(w2,h2))
# Calculating starting width, if you want to insert data in middle of image, calculate height in similar fashion:
textX1 = int((iw - w1) / 2)
textX2 = int((iw - w2) / 2)
# lines to wrap text beyond width
lines1 = textwrap.wrap(text1, width=40)
lines2 = textwrap.wrap(text2, width=40)
# breather to adjust height change for text wrap
breather = (len(lines1)-1)*h1 + (len(lines2) -1)*h2
y_text1 = h1
for line in lines1:
width, height = font1.getsize(line)
draw.text((int((iw - width) / 2), startHeight - breather +y_text1), line, font=font1)
y_text1 += height
y_text2 = y_text1+10
for line in lines2:
width, height = font2.getsize(line)
draw.text((int((iw - width) / 2), startHeight - breather +y_text2), line, font=font2)
y_text2 += height
# draw.text((textX1, 850), text1, font=font1, fill=color)
# draw.text((textX2, 850+h1+10), text2, font=font2, fill=color)
image.save("output.jpg")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment