Created
March 16, 2020 05:22
-
-
Save namieluss/a0191b56f0c437514fb3ab91f70317a4 to your computer and use it in GitHub Desktop.
Add watermark to an Image using Python Pillow
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, ImageDraw, ImageFont | |
# open image to apply watermark to | |
img = Image.open("watermark_test.jpg") | |
img.convert("RGB") | |
# get image size | |
img_width, img_height = img.size | |
# 5 by 4 water mark grid | |
wm_size = (int(img_width * 0.20), int(img_height * 0.25)) | |
wm_txt = Image.new("RGBA", wm_size, (255, 255, 255, 0)) | |
# set text size, 1:40 of the image width | |
font_size = int(img_width / 40) | |
# load font e.g. gotham-bold.ttf | |
font = ImageFont.truetype(path.format("gotham-bold.ttf"), font_size) | |
d = ImageDraw.Draw(wm_txt) | |
wm_text = "Kuma Kum" | |
# centralize text | |
left = (wm_size[0] - font.getsize(wm_text)[0]) / 2 | |
top = (wm_size[1] - font.getsize(wm_text)[1]) / 2 | |
# RGB(0, 0, 0) is black | |
# Alpha channel specifies the opacity for a color | |
alpha = 75 | |
d.text((left, top), wm_text, fill=(0, 0, 0, alpha), font=font) | |
# uncomment to rotate watermark text | |
# wm_txt = wm_txt.rotate(15, expand=1) | |
# wm_txt = wm_txt.resize(wm_size, Image.ANTIALIAS) | |
for i in range(0, img_width, wm_txt.size[0]): | |
for j in range(0, img_height, wm_txt.size[1]): | |
img.paste(wm_txt, (i, j), wm_txt) | |
# save image with watermark | |
img.save("watermark-image-1.jpg") | |
# show image with watermark in preview | |
img.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment