Skip to content

Instantly share code, notes, and snippets.

@jbcdnr
Created October 10, 2017 16:19
Show Gist options
  • Save jbcdnr/60703d5737cc3282867506226c88873d to your computer and use it in GitHub Desktop.
Save jbcdnr/60703d5737cc3282867506226c88873d to your computer and use it in GitHub Desktop.
Script to watermark a folder of images
import argparse
import subprocess
import glob
import os
from os import path
from PIL import Image, ExifTags
import math
# check that imagemagick is installed
try:
subprocess.check_output(['convert', '-version'])
except Exception as e:
print("Please install imagemagick")
exit(1)
raise e
parser = argparse.ArgumentParser(description='Watermark some photos')
parser.add_argument('logo', type=str, help='watermark logo to add')
parser.add_argument('input_dir', type=str, help='directory with the pictures')
parser.add_argument('output_dir', type=str, help='destination directory')
parser.add_argument('--margin', type=int, default=100, help='margin between logo and border')
parser.add_argument('--area-ratio', type=float, default=1/25, help='ratio of space for the watermark')
args = parser.parse_args()
def rotate(img):
# find orientation tag
for orientation in ExifTags.TAGS.keys() :
if ExifTags.TAGS[orientation] == 'Orientation':
break
exif=dict(img._getexif().items())
img2 = img
if exif[orientation] == 3 :
img2 = img.rotate(180, expand=True)
elif exif[orientation] == 6 :
img2 = img.rotate(270, expand=True)
elif exif[orientation] == 8 :
img2 = img.rotate(90, expand=True)
return img2
# create output dir if does not exists
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
files = glob.glob(args.input_dir + '/*')
n = len(files)
original_watermark = Image.open(args.logo).convert('RGBA')
w_original_width, w_original_height = original_watermark.size
w_original_area = w_original_width * w_original_height
w_ratio = w_original_width / w_original_height
# image size -> watermark resized
already_resized = {}
for i, f in enumerate(files):
name = path.basename(f)
out = path.join(args.output_dir, name)
print(f, '... processing ... ', end='')
photo = Image.open(f)
photo = rotate(photo)
width, height = photo.size
if (width, height) not in already_resized:
w_area = args.area_ratio * width * height
w_height = math.sqrt(w_area / w_ratio)
w_width = int(w_height * w_ratio)
w_height = int(w_height)
new_watermark = original_watermark.resize((w_width, w_height), Image.ANTIALIAS)
already_resized[width * height] = new_watermark
watermark = already_resized[width * height]
w_width, w_height = watermark.size
photo.paste(watermark, (width - w_width - args.margin, height - w_height - args.margin), watermark)
photo.save(out)
print('done {}/{}'.format(i+1, n))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment