Skip to content

Instantly share code, notes, and snippets.

@jontwo
Created December 19, 2021 15:47
Show Gist options
  • Save jontwo/c2738da9a572293caa58c3860e95d959 to your computer and use it in GitHub Desktop.
Save jontwo/c2738da9a572293caa58c3860e95d959 to your computer and use it in GitHub Desktop.
Adds a border to image files ready for uploading to Instagram. Required Python Pillow/PIL library to be installed. Output image size, border size, and image size as proportion of output are hardcoded - alter according to your needs!
"""Adds a border to image files ready for uploading to Instagram."""
import os
import sys
from PIL import Image, ImageDraw
# output image and border sizes in pixels
WIDTH = HEIGHT = 3000
BORDER = 0
# original image size as proportion of output size
IMG_PROP = 0.9
def main(args):
if not args:
print('Usage: add_border.py <path to image>')
return
for in_path in args:
fname, ext = os.path.splitext(in_path)
if fname.endswith('_border'):
print(f"Skipping {in_path}")
continue
with Image.open(in_path) as img:
width, height = img.size
ratio = WIDTH / max(width, height)
new_width = int(round(IMG_PROP * ratio * width))
new_height = int(round(IMG_PROP * ratio * height))
img_x = int(round((WIDTH / 2) - (new_width / 2)))
img_y = int(round((WIDTH / 2) - (new_height / 2)))
new_img = Image.new("RGB", (WIDTH, HEIGHT), (255,255,255))
if BORDER:
border_width = new_width + BORDER * 2
border_height = new_height + BORDER * 2
bx0 = int(round((WIDTH / 2) - (border_width / 2)))
by0 = int(round((WIDTH / 2) - (border_height / 2)))
bx1 = int(round((WIDTH / 2) + (border_width / 2)))
by1 = int(round((WIDTH / 2) + (border_height / 2)))
d = ImageDraw.Draw(new_img)
d.rectangle([(bx0, by0), (bx1, by1)], fill='black', outline='black')
img_resized = img.resize((new_width, new_height))
new_img.paste(img_resized, box=(img_x, img_y))
out_path = f'{fname}_border{ext}'
new_img.save(out_path)
if __name__ == '__main__':
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment