Created
January 26, 2020 05:52
-
-
Save ponnamkarthik/7179c33f03a99918017936119a414de8 to your computer and use it in GitHub Desktop.
Python Script to Listen a folder for new file (Image) and add a watermark
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
from PIL import Image | |
import sys | |
import time | |
from watchdog.observers import Observer | |
from watchdog.events import FileSystemEventHandler | |
def watermark_photo(input_image_path, | |
output_image_path, | |
watermark_image_path): | |
# Read image file | |
base_image = Image.open(input_image_path) | |
# Get sizes of image | |
width, height = base_image.size | |
# Get watermark image | |
watermark = Image.open(watermark_image_path) | |
# Resize Watermark image | |
watermark = watermark.resize((150,150)) | |
# Position to place watermark | |
position = (width - 150, height - 150) | |
# Convert imaget to handle transparency | |
transparent = Image.new('RGBA', (width, height), (0,0,0,0)) | |
transparent.paste(base_image, (0,0)) | |
# Add watermark to image | |
transparent.paste(watermark, position, mask=watermark) | |
# convert image back to RGB to save as JPG | |
transparent = transparent.convert("RGB") | |
# Save as JPG | |
transparent.save(output_image_path) | |
print(f"Watermark added on {output_image_path}") | |
class FileHandle(FileSystemEventHandler): | |
def on_modified(self, event): | |
pass | |
def on_created(self,event): | |
# On New file created | |
path = str(event.src_path).replace(".\\", "") | |
time.sleep(1) | |
watermark_photo(path, path, 'logo.png') | |
if __name__ == "__main__": | |
path = sys.argv[1] if len(sys.argv) > 1 else '.' | |
event_handler = FileHandle() | |
observer = Observer() | |
observer.schedule(event_handler, path, recursive=True) | |
observer.start() | |
try: | |
while True: | |
time.sleep(1) | |
except KeyboardInterrupt: | |
observer.stop() | |
observer.join() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment