Sleepy Weim

Python: Countdown Image

In this example of my script I have a Disney and a Christmas countdown to show you the differences between a customized and a plain countdown. Even my plain countdown has a font specified.

As with my previous code, you need to have Pillow installed.

For the custom fonts, I added a ‘fonts’ folder in my script folder, and added the files there. On my Mac, I can open ‘Font Book’, look at my fonts, find the file for the font I want, and then copy it over to the scripting location. Windows has similar abilities, or you can download free fonts from the web.

Notice that for the Disney date, I open an image I have created for the background, but for Christmas I simple generate a new image with a simple colored background.

import time

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw 

from datetime import datetime

def days_between(d1, d2):
    d1 = datetime.strptime(d1, "%m/%d/%Y")
    d2 = datetime.strptime(d2, "%m/%d/%Y")
    return abs((d2 - d1).days)

#
# Date objects
#
disney = '10/31/2019'
christmas = '12/25/2019'
today = time.strftime("%m/%d/%Y")

#
# Image Object Sizing
#
imgHeight = 300
imgWidth = 150

#
# Countdown for your date
#
disney_countdown = str(days_between(today, disney))
christmas_countdown = str(days_between(today, christmas))

#
# Create image for Disney countdown
#
img = Image.open('/volume1/files/Scripting/mickey_tile_header.jpg')
draw = ImageDraw.Draw(img)

# font = ImageFont.truetype(<font-file>, <font-size>)
font = ImageFont.truetype("/volume1/files/Scripting/fonts/waltograph42.otf", 100)

ascent, descent = font.getmetrics()
(width, baseline), (offset_x, offset_y) = font.font.getsize(disney_countdown)

textHeight = ascent - offset_y
textWidth = font.getmask(disney_countdown).getbbox()[2] 

# draw.text((x, y),"Sample Text",(r,g,b))
draw.text(((imgWidth - textWidth)/2, ((imgHeight - textHeight)/2 + 15)),disney_countdown,(255,0,0),font=font)

img.save('/volume1/web/actiontiles/countdown_disney.jpg')

# *****************************

#
# Create image for Christmas countdown
#
img = Image.new('RGB', (imgWidth, imgHeight), (120, 120, 120))
draw = ImageDraw.Draw(img)

# font = ImageFont.truetype(<font-file>, <font-size>)
font = ImageFont.truetype("/volume1/files/Scripting/fonts/The Perfect Christmas.ttf", 140)

ascent, descent = font.getmetrics()
(width, baseline), (offset_x, offset_y) = font.font.getsize(christmas_countdown)

textHeight = ascent - offset_y
textWidth = font.getmask(christmas_countdown).getbbox()[2] 

# draw.text((x, y),"Sample Text",(r,g,b))
draw.text(((imgWidth - textWidth)/2, (imgHeight - textHeight)/2),christmas_countdown,(0,255,0),font=font)

img.save('/volume1/web/actiontiles/countdown_christmas.jpg')

Leave a Reply