Skip to content

Instantly share code, notes, and snippets.

@Aameer
Last active March 1, 2018 17:51
Show Gist options
  • Save Aameer/8ed0207a74d906cbb585 to your computer and use it in GitHub Desktop.
Save Aameer/8ed0207a74d906cbb585 to your computer and use it in GitHub Desktop.
watermark text over images using Python with PIL and textwrap, by tweaking the widths you can control the max length of text allowed and it also does the word wrap and shows extra text in next line
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import textwrap
base_image_location = "/home/aameer/Desktop/test.png" #base image location
W,H=(900, 100) #width and height of base image
font_location = "/home/aameer/Desktop/verdanab.ttf" #font used
output_image_location='/home/aameer/Desktop/' #location where output file will be stored
def create_watermark_image(text):
#allowing one line of 35 chars and based on our height
#we can fine tune to accomodate different number of lines thus total chars limit too
para = textwrap.wrap(text,width=35)
#white
text_color=(0, 0, 0,64)
text_font = ImageFont.truetype(font_location,33)
image = Image.open(base_image_location)
d = ImageDraw.Draw(image)
#padding and height for the lines breaking the text into several lines
current_h, pad = 20, 2
for line in para:
w, h = d.textsize(line, font=text_font)
d.text(((W - w) / 2, current_h), line, fill=text_color,font=text_font)
current_h += h + pad
image.save(output_image_location+'overlayedimage.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment