-
Notifications
You must be signed in to change notification settings - Fork 5
/
add_border_8.py
51 lines (42 loc) · 1.13 KB
/
add_border_8.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""Add a border to any image."""
import sys
from pathlib import Path
from PIL import Image, ImageOps, UnidentifiedImageError
# Get the filename.
try:
path = Path(sys.argv[1])
except IndexError:
print("You must provide a target image.")
sys.exit()
# --- Get optional CLI args. ---
try:
border_width = int(sys.argv[2])
except IndexError:
border_width = 2
try:
padding = int(sys.argv[3])
except IndexError:
padding = 0
try:
border_color = sys.argv[4]
except IndexError:
border_color = "lightgray"
# Load the image.
try:
img = Image.open(path)
except FileNotFoundError:
print(f"{path} does not seem to exist.")
sys.exit()
except UnidentifiedImageError:
print(f"{path} does not seem to be an image file.")
sys.exit()
# Add some padding before adding the border.
# The padding is just a white border added before
# the actual border.
new_img = ImageOps.expand(img, border=padding, fill="white")
# Add the border.
new_img = ImageOps.expand(new_img, border=border_width,
fill=border_color)
# Save new image.
new_path = path.parent / f"{path.stem}_bordered{path.suffix}"
new_img.save(new_path)