Skip to content

Instantly share code, notes, and snippets.

@philmikejones
Created August 30, 2018 15:14
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philmikejones/c2465a992b678e7fde464caed60dd569 to your computer and use it in GitHub Desktop.
Save philmikejones/c2465a992b678e7fde464caed60dd569 to your computer and use it in GitHub Desktop.
Layout multiple images onto one canvas with Python pillow
## Pastes Lexis surface diagrams and HAPC plots together
import os
import glob
from subprocess import call
from PIL import Image, ImageDraw, ImageFont
# Get country code list
countries = glob.glob("mort_*.png")
countries = sorted(countries)
## http://stackoverflow.com/questions/3136689/find-and-replace-string-values-in-python-list
## Get the country codes
countries = [countries.replace("mort_", "") for countries in countries]
countries = [countries.replace(".png", "") for countries in countries]
# Set output canvas size
dpi = 300
width = int((42.0 / 2.54) * dpi)
height = int((29.7 / 2.54) * dpi)
for i in countries:
# Create blank canvas
canvas = Image.new("RGBA", (width, height), color = (255, 255, 255))
# Open Lexis surface plot, trim whitespace, paste into canvas
lexis = Image.open("mort_" + i + ".png")
canvas.paste(lexis)
# Lexis plots place females on left; males on right
# Copy this layout for HAPC plots
# Paste in HAPC female plot
pastex = 0
pastey = int(height / 2)
hapc_female = Image.open("cohort_" + i + "_female.png")
canvas.paste(hapc_female, box = (pastex, pastey))
# Paste in HAPC male plot
pastex = int(width / 2)
hapc_male = Image.open("cohort_" + i + "_male.png")
canvas.paste(hapc_male, box = (pastex, pastey))
# Add annotations
draw = ImageDraw.Draw(canvas)
font = ImageFont.truetype("FreeMono.ttf", 100)
draw.text((20, 20), "Country: " + i,
fill = (0, 0, 0, 255), font = font)
# Save
filename = "country_" + i + ".png"
canvas.save(filename)
@kareemjeiroudi
Copy link

kareemjeiroudi commented Nov 1, 2019

This is great! Where do you provide the data so that I can try out your code?

@philmikejones
Copy link
Author

You just need four images, each about 210x148.5mm (A5) landscape. Although you can of course modify the script to use any number/size images you like

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment