This is Day 3 of the #100DaysOfPython challenge.
This post will use the Pillow image library to add text and icons layers to an image programmatically.
- An image that is 1000x600 pixels.
- Some demo icons 100x100 pixels.
- Familiarity with [Pipenv]. See here for my post on Pipenv.
- Familiarity with JupyterLab. See here for my post on JupyterLab.
- Open Sans Bold font installed to
Let’s create the
hello-img-layers directory and install Pillow.
At this stage, add your 1000x600 image to the root directory (
base_img.png (at least that is what I am using) and add your 100x100 icons to
Now we can start up the notebook server.
The server will now be up and running.
Creating the notebook
Once on http://localhost:8888/lab, select to create a new Python 3 notebook from the launcher.
Ensure that this notebook is saved in
We will create four cells to handle four parts of this mini project:
- Load the image in.
- Creating the destination image and adding the icon layers.
- Creating the text layer.
- Saving and displaying the destination image.
Loading in the image
This section simply loads the image in var
base_img (assuming you are following the directory structure where the notebook is in the
Creating the destination image and adding the icon layers
We create the destination layer here based on the base images width and height and paste that base image back in.
Then we make use of the glob library to fetch all the paths to our icons and paste them on top of the base image.
Creating the text layer
This layer will load our
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.
Saving and displaying the destination image
Finally, we will save and display our base image.
Today’s post demonstrated how to use the
Pillow package to add text and icons layers to an image programmatically.
This will be the technique I use for helping to build out my blog post main images (including this one!).
Resources and further reading
Originally posted on my blog. To see new posts without delay, read the posts there and subscribe to my newsletter.