-
-
Save sonpython/9f44a60a62a66fe80688bc5ba4cdd7b6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
__author__ = "Mark Allan B. Meriales" | |
# based from http://www.pythoncentral.io/watermark-images-python-2x/ | |
# mine uses a picture as a watermark | |
# michaelphan add base_ratio for logo and better logo scale | |
from PIL import Image, ImageEnhance | |
def add_watermark(image_file, logo_file, opacity=1): | |
img = Image.open(image_file).convert('RGB') | |
logo = Image.open(logo_file) | |
# TODO: add aspect ratio as an argument | |
base_w = (img.size[0]/5) / float(logo.size[0]) | |
base_h = (img.size[0]/8) / float(logo.size[1]) | |
base_ratio = min(base_w, base_h) | |
logo_w = int(float(logo.size[0]) * float(base_ratio)) | |
logo_h = int(float(logo.size[1]) * float(base_ratio)) | |
logo = logo.resize((logo_w, logo_h), Image.ANTIALIAS) | |
# position the watermark | |
offset_x = (img.size[0] - logo.size[0]) - 10 | |
offset_y = (img.size[1] - logo.size[1]) - 10 | |
watermark = Image.new('RGBA', img.size, (255, 255, 255, 1)) | |
watermark.paste(logo, (offset_x, offset_y), mask=logo.split()[3]) | |
alpha = watermark.split()[3] | |
alpha = ImageEnhance.Brightness(alpha).enhance(opacity) | |
watermark.putalpha(alpha) | |
Image.composite(watermark, img, watermark).save(image_file, 'JPEG') | |
return image_file |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment