23
loading...
This website collects cookies to deliver better user experience
This is Day 3 of the #100DaysOfPython challenge.
fonts/OpenSans-Bold.ttf
.hello-img-layers
directory and install Pillow.# Make the `hello-img-layers` directory
$ mkdir hello-img-layers
$ cd hello-img-layers
# Create a folder to place your icons
$ mkdir icons
# Init the virtual environment
$ pipenv --three
$ pipenv install pillow
$ pipenv install --dev jupyterlab
hello-img-layers
) as base_img.png
(at least that is what I am using) and add your 100x100 icons to hello-img-layers/icons/
.# Startup the notebook server
$ pipenv run jupyter-lab
# ... Server is now running on http://localhost:8888/lab
hello-img-layers/docs/<your-file-name>
.base_img
(assuming you are following the directory structure where the notebook is in the docs
folder).from PIL import Image
# Concatenating an image
base_img = Image.open('../base_img.png')
# Add in icons using a glob
import glob
from os.path import join, dirname, abspath
dst_img = Image.new('RGBA', (base_img.width, base_img.height))
dst_img.paste(base_img, (0, 0))
icons_dir = join(dirname(abspath("__file__")), '../icons')
icons = glob.glob(f"{icons_dir}/*")
for i, icon_path in enumerate(icons):
icon = Image.open(icon_path)
# @see https://stackoverflow.com/questions/5324647/how-to-merge-a-transparent-png-image-with-another-image-using-pil
dst_img.paste(icon, (60 + (i * icon.width) + (i * 20), base_img.height - 100 - icon.height), icon)
Open Sans
font and draw that onto the image.max_text_width=25
that I selected here was through trial and error. There may be a more reusable way to handle this for different sized images.import os
# Add your own font in
font = ImageFont.truetype(os.path.join('fonts/OpenSans-Bold.ttf'), 58)
import textwrap
text = "Sample Text that is too long but let us write a bunch anyway"
print(dst_img.width)
max_text_width = 25
wrapped_text = textwrap.wrap(text, width=max_text_width)
# setup up a variable to invoke our text method
draw = ImageDraw.Draw(dst_img)
for i, line in enumerate(wrapped_text):
# draw.text((0, height - (i * 20)), line, (0, 0, 0), font=font)
draw.text((60, 100 + (i * 80)),line,(255,255,255),font=font)
dst_img.save('../dest_img.png')
# Display the image inline
display(Image.open('../dest_img.png'))
Pillow
package to add text and icons layers to an image programmatically.