Guest User

seatingCards.py

a guest
Oct 1st, 2018
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.40 KB | None | 0 0
  1. #! python3
  2. # seatingCards.py - This program creates images for custom seating cards for a list of guests.
  3. #
  4. # This code is part of a list of corrections on reddit at:
  5. # https://www.reddit.com/r/inventwithpython/comments/8ykq1i/automate_the_boring_stuff_with_python_corrections/
  6. # -/u/JoseALerma
  7. #
  8. # Note:
  9. # - flowery decoration from: http://www.reusableart.com/flower-02.html
  10.  
  11. import os
  12. from PIL import Image, ImageFont, ImageDraw
  13.  
  14. GUEST_FILE = '../../Chapter13/PracticeProjects/guests.txt'
  15. FLOWER_FILENAME = 'flower-02.png'
  16. OUTPUT_FOLDER = 'seatingCards'
  17. FONTS_FOLDER = '/usr/share/fonts/truetype'
  18.  
  19. os.makedirs(OUTPUT_FOLDER, exist_ok=True)
  20. # Get guest list from file
  21. with open(GUEST_FILE) as guest_list:
  22.     guests = guest_list.read().splitlines()
  23.  
  24.  
  25. for guest in guests:
  26.     # Open flowery decoration
  27.     deco = Image.open(FLOWER_FILENAME)
  28.     deco_width, deco_height = deco.size
  29.  
  30.     # Resize decoration if smaller than 4x5-inch card
  31.     if deco_width < 288 or deco_height < 360:
  32.         # Calculate the new width and height to resize to
  33.         if deco_width > deco_height:
  34.             deco_height = int((288 / deco_width) * deco_height)
  35.             deco_width = 288
  36.         else:
  37.             deco_width = int((360 / deco_height) * deco_width)
  38.             deco_height = 360
  39.         print('Resizing decoration...')
  40.         deco = deco.resize((deco_width, deco_height), Image.ANTIALIAS)
  41.         deco = deco.convert(mode='L')  # Convert back to grayscale (if original image is grayscale)
  42.  
  43.     # Add guest's name
  44.     draw = ImageDraw.Draw(deco)
  45.     if u'\u014d' in guest:  # Replace ō with o since draw.textsize can't translate it
  46.         guest = guest.replace(u'\u014d', 'o')
  47.     text_width, text_height = draw.textsize(guest)
  48.     font = ImageFont.truetype(os.path.join(FONTS_FOLDER, '/liberation/LiberationSerif-Regular.ttf'), 15)
  49.     draw.text((int((deco_width - text_width) / 2), int((deco_height - text_height) / 2)), guest, fill='black'
  50.               , font=font)
  51.  
  52.     # Make black card with extra space for cutting
  53.     image = Image.new('RGBA', (deco_width + 10, deco_height + 10), 'black')
  54.     width, height = image.size
  55.  
  56.     # Add modified decoration to background
  57.     image.paste(deco, (int((width - deco_width) / 2), int((height - deco_height) / 2)))
  58.  
  59.     # Save seating card
  60.     filename = ''.join(filter(str.isalnum, guest)) + '.png'
  61.     image.save(os.path.join(OUTPUT_FOLDER, filename))
Add Comment
Please, Sign In to add comment