Skip to content

Instantly share code, notes, and snippets.

@liushuaikobe
Created August 20, 2018 11:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liushuaikobe/c919cdf001f76d7d7ba4c259bcc2b1af to your computer and use it in GitHub Desktop.
Save liushuaikobe/c919cdf001f76d7d7ba4c259bcc2b1af to your computer and use it in GitHub Desktop.
Add text.
import sys
import uuid
import textwrap
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
def generate(img, text):
# open image
i = Image.open(img)
# calc target size
base_width = 160
percent = base_width / float(i.size[0])
target_height = int((float(i.size[1]) * float(percent)))
i = i.resize((base_width, target_height), Image.ANTIALIAS)
draw = ImageDraw.Draw(i)
# paragraph
para = textwrap.wrap(text, width=8)
# font
font = ImageFont.truetype("PingFang.ttc", 16)
# draw text
vertical_center_offset = 10
current_height = target_height / 2.0 + vertical_center_offset
line_padding = 2
for line in para:
w, h = draw.textsize(line, font=font)
draw.text(((base_width - w) / 2.0, current_height), line, (255, 0, 0), font=font)
current_height += h + line_padding
i.save(str(uuid.uuid4()) + '.png')
def main(img, text=()):
for t in text:
generate(img, t.decode('utf-8'))
if __name__ == '__main__':
main(sys.argv[1], tuple(sys.argv[2:]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment