Created
May 14, 2022 03:09
-
-
Save arx8x/5eaf33a6a14f97bf6cb8d5e737f8d9be to your computer and use it in GitHub Desktop.
This file contains 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 | |
# 0.2 = take max 20% of the canvas size | |
thumbnail_factor = 0.2 | |
watermark_padding = 0.05 | |
# (w, h) | |
POS_TOPLEFT = (0, 0) | |
POS_TOPRIGHT = (1, 0) | |
POS_BOTTOMLEFT = (0, 1) | |
POS_BOTTOMRIGHT = (1, 1) | |
def watermark_dimensions(canvas_size: tuple, watermark_size: tuple): | |
thumbnail_max_side = thumbnail_factor * min(canvas_size[0], canvas_size[1]) | |
scale = min(thumbnail_max_side / watermark_size[0], thumbnail_max_side / watermark_size[1]) | |
w = scale * watermark_size[0] | |
h = scale * watermark_size[1] | |
return (int(w), int(h)) | |
def corner_coordinates(canvas_size: tuple, watermark_size: tuple, corner: tuple): | |
padding_pixels = min(canvas_size[0], canvas_size[1]) * watermark_padding | |
# side type 0 is width, 1 is height | |
def calc_side(side_type): | |
side = 0 | |
if not corner[side_type]: | |
side += padding_pixels | |
else: | |
offset = watermark_size[side_type] + padding_pixels | |
side = canvas_size[side_type] - offset | |
return side | |
w = calc_side(0) | |
h = calc_side(1) | |
return (int(w), int(h)) | |
background = Image.open('bg.jpg') | |
watermark = Image.open('watermark.png') | |
# calculate the watermark dimentions in relation with | |
# the backgroud/canvas size | |
wm_size = watermark_dimensions(background.size, watermark.size) | |
# resize the watermark | |
watermark = watermark.resize(wm_size) | |
# find the coordinates for corners | |
# the way I programmed the corners is 'adoptable' | |
# with slight adjustments to the math | |
# an alignment logic can also be added to make things nicer | |
corner_wh = corner_coordinates(background.size, watermark.size, POS_BOTTOMLEFT) | |
# actually, this isn't the overlay. This is the actual image being stamped on | |
# the overlay is the watermark that masks this solid color layer | |
# replace 'color_overlay' with 'watermark' to get the actual image as watermark | |
color_overlay = Image.new('RGB', wm_size, (130, 130, 130)) | |
background.paste(color_overlay, corner_wh, mask=watermark) | |
background.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment