Skip to content

Instantly share code, notes, and snippets.

@NaikSoftware
Last active November 6, 2016 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NaikSoftware/26ed7f95ef8ecd7b9f365195b903588e to your computer and use it in GitHub Desktop.
Save NaikSoftware/26ed7f95ef8ecd7b9f365195b903588e to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import colorsys
import getopt
from tempfile import NamedTemporaryFile
import sys
from wand.image import Image
import os
COMPRESSION_QUALITY = 98
TOP_OFFSET = 19.0 / 20.0
LEFT_OFFSET = 1.0 / 20.0
WATERMARK_HEIGHT = 1.0 / 18.0
def main(watermark, source_dir, destination_dir, recursive=False):
destination_dir = destination_dir.rstrip(os.sep)
source_dir = source_dir.rstrip(os.sep)
mark = Image(filename=watermark)
mark_ratio = mark.width / mark.height
for idx, (root, dirs, files) in enumerate(os.walk(source_dir, topdown=True)):
if idx > 0 and not recursive: break
print 'Watermarking dir %s' % root
folder_path = root.replace(source_dir, '')
if len(folder_path) == 0:
save_dir = destination_dir + os.sep
else:
if not folder_path.endswith(os.sep): folder_path += os.sep
save_dir = destination_dir + folder_path
if not os.path.exists(save_dir): os.mkdir(save_dir)
for file_name in files:
watermark_image(mark, mark_ratio, root + os.sep + file_name, save_dir + file_name)
mark.close()
print 'Finished';
def median_color(file_name):
# Get string 'srgb(r,g,b)'
out = os.popen("convert '{}' -scale 1x1\! -format '%[pixel:u]' info:-".format(file_name)).read()
return map(lambda c: int(c), out.strip().replace('srgb(', '').replace(')', '').split(','))
# def text_color_for_background(hsv):
# return (hsv[0] + 180) % 360, \
# 20.0 if 45 < hsv[1] < 55 else (hsv[1] + 50) % 100, \
# 20.0 if 45 < hsv[2] < 55 else (hsv[2] + 50) % 100
def watermark_image(watermark, watermark_ratio, file_name, dest_file_name):
try:
with Image(filename=file_name) as img:
mark_height = int(img.height * WATERMARK_HEIGHT)
mark_width = (mark_height * watermark_ratio)
resized_mark = watermark.clone()
resized_mark.resize(mark_width, mark_height, filter='gaussian')
# with Drawing() as draw:
# draw.composite(operator='soft_light', left=int(img.width * LEFT_OFFSET),
# top=int(img.height * TOP_OFFSET),
# width=resized_mark.width,
# height=resized_mark.height,
# image=resized_mark)
# draw(img)
with img.clone() as mark_background:
mark_background.crop(left=int(img.width * LEFT_OFFSET), top=int(img.height * TOP_OFFSET),
width=resized_mark.width, height=resized_mark.height)
temp_file = NamedTemporaryFile(delete=False)
mark_background.save(filename=temp_file.name)
median = median_color(file_name)
os.unlink(temp_file.name)
hsv = colorsys.rgb_to_hsv(median[0] / 255.0, median[1] / 255.0, median[2] / 255.0)
# hsv = (360 * hsv[0], 100 * hsv[1], 100 * hsv[2])
# print hsv
# text_color = text_color_for_background(hsv)
img.watermark(resized_mark, 1 - hsv[2], left=int(img.width * LEFT_OFFSET), top=int(img.height * TOP_OFFSET))
img.compression_quality = COMPRESSION_QUALITY
img.save(filename=dest_file_name)
resized_mark.close()
except:
print '\t- Can not watermark file %s, ignoring' % file_name
else:
print '\t- Watermarked successfully file %s' % file_name
def print_help():
print """ Utility for watermarking images. Usage:
-m, --mark \t Path to image watermark
-s, --source \t Path to directory with source images, default ./
-d, --dest \t Path to destination directory for images
-r, --recursive \t Recursive watermark source directory
-h, --help \t Print this help
"""
if __name__ == "__main__":
watermark = None
source = './'
destination = None
recursive = False
try:
opts, args = getopt.getopt(sys.argv[1:], 'hw:s:d:r', ['help', 'watermark=', 'source=', 'dest=', 'recursive'])
except getopt.GetoptError:
print 'Usage error, see help (--help or -h)'
sys.exit(0)
for opt, value in opts:
if opt == '-h' or opt == '--help':
print_help()
sys.exit()
elif opt == '-w' or opt == '--watermark':
watermark = value
elif opt == '-s' or opt == '--source':
source = value
elif opt == '-d' or opt == '--dest':
destination = value
elif opt == '-r' or opt == '--recursive':
recursive = True
if watermark is None:
print 'Pass path to watermark image (-w)'
sys.exit()
elif destination is None:
print 'Pass destination directory (-d)'
sys.exit()
main(watermark, source, destination, recursive)
@NaikSoftware
Copy link
Author

Write watermark picture on bottom down position of image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment