|
| 1 | +#! /usr/bin/python3.5 |
| 2 | + |
| 3 | + |
| 4 | +""" |
| 5 | +
|
| 6 | +Author: Samrat Banerjee |
| 7 | +Dated: 10/09/2018 |
| 8 | +Description: Project: Resizes all images in current working directory to fit in a 300x300 square, and adds catlogo.png to the lower-right corner |
| 9 | +
|
| 10 | +""" |
| 11 | + |
| 12 | +import os |
| 13 | +from PIL import Image |
| 14 | + |
| 15 | +SQUARE_FIT_SIZE = 300 |
| 16 | +LOGO_FILENAME = 'catlogo.png' |
| 17 | + |
| 18 | +logoIm = Image.open(LOGO_FILENAME) |
| 19 | +logoWidth, logoHeight = logoIm.size |
| 20 | + |
| 21 | +os.makedirs('withLogo', exist_ok=True) |
| 22 | +# Loop over all files in the working directory. |
| 23 | +for filename in os.listdir('.'): |
| 24 | + if not (filename.endswith('.png') or filename.endswith('.jpg')) or filename == LOGO_FILENAME: |
| 25 | + continue # skip non-image files and the logo file itself |
| 26 | + |
| 27 | + im = Image.open(filename) |
| 28 | + width, height = im.size |
| 29 | + |
| 30 | + # Check if image needs to be resized. |
| 31 | + if width > SQUARE_FIT_SIZE and height > SQUARE_FIT_SIZE: |
| 32 | + # Calculate the new width and height to resize to. |
| 33 | + if width > height: |
| 34 | + height = int((SQUARE_FIT_SIZE / width) * height) |
| 35 | + width = SQUARE_FIT_SIZE |
| 36 | + else: |
| 37 | + width = int((SQUARE_FIT_SIZE / height) * width) |
| 38 | + height = SQUARE_FIT_SIZE |
| 39 | + |
| 40 | + |
| 41 | + # Resize the image. |
| 42 | + print('Resizing %s...' % (filename)) |
| 43 | + im = im.resize((width, height)) |
| 44 | + |
| 45 | + # Add the logo. |
| 46 | + print('Adding logo to %s...' % (filename)) |
| 47 | + im.paste(logoIm, (width - logoWidth, height - logoHeight), logoIm) |
| 48 | + |
| 49 | + # Save changes. |
| 50 | + im.save(os.path.join('withLogo', filename)) |
0 commit comments