Skip to content

Instantly share code, notes, and snippets.

@jamesoutterside
Created January 21, 2013 13:19
Show Gist options
  • Save jamesoutterside/4585978 to your computer and use it in GitHub Desktop.
Save jamesoutterside/4585978 to your computer and use it in GitHub Desktop.
Uses pil to stamp and image with a license banner
# stanp a license bar at the bottom of an image
from PIL import Image, ImageFont, ImageDraw
import settings
def stamp_image(in_filepath, out_filepath,text):
im = Image.open(in_filepath)
# get size
original_size = im.size
o_width = original_size[0]
o_height = original_size[1]
# calc additional space size
line = 15 # height per line
add_size = (len(text) / (o_width/10)) * line # chars per line
# min size
if add_size < 20:
add_size = 20
new_size = (im.size[0], im.size[1] + add_size)
# create blank image with 50px space at the bottom.
im2 = Image.new("RGBA", new_size, 'Black')
im2.paste(im, (0,0))
# write copywrite text
draw_word_wrap(img = im2,
text = text,
xpos = 5,
ypos = im.size[1]+5,
max_width = im2.size[0]-5,
fill='White',
font=ImageFont.load_default())
# save the image
im2.save(out_filepath, "JPEG")
def draw_word_wrap(img, text, xpos=0, ypos=0, max_width=130, fill=(0,0,0), font=None):
'''Draw the given ``text`` to the x and y position of the image, using
the minimum length word-wrapping algorithm to restrict the text to
a pixel width of ``max_width.``
'''
draw = ImageDraw.Draw(img)
text_size_x, text_size_y = draw.textsize(text, font=font)
remaining = max_width
space_width, space_height = draw.textsize(' ', font=font)
# use this list as a stack, push/popping each line
output_text = []
# split on whitespace...
for word in text.split(None):
word_width, word_height = draw.textsize(word, font=font)
if word_width + space_width > remaining:
output_text.append(word)
remaining = max_width - word_width
else:
if not output_text:
output_text.append(word)
else:
output = output_text.pop()
output += ' %s' % word
output_text.append(output)
remaining = remaining - (word_width + space_width)
for text in output_text:
draw.text((xpos, ypos), text, font=font, fill=fill)
ypos += text_size_y
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment