code on python, watermarking in the centre of a photo
- User
code on python, watermarking in the centre of a photo
- Assistant
code on python, watermarking in the centre of a photo
Certainly! To add a watermark in the center of an image using Python, you can use the Pillow library, which is a fork of the Python Imaging Library (PIL). First, you'll need to install Pillow if you haven't already:
pip install Pillow
Here's a simple example of how to add a text watermark in the center of an image:
from PIL import Image, ImageDraw, ImageFont
def add_watermark(input_image_path, output_image_path, watermark_text):
# Open the original image
original = Image.open(input_image_path).convert("RGBA")
# Create a transparent layer for the watermark
txt = Image.new('RGBA', original.size, (255, 255, 255, 0))
# Set up the drawing context
draw = ImageDraw.Draw(txt)
# Load a font
# Make sure to specify a .ttf font file path
font_size = 36
try:
# Use a truetype font (you may have to change the font file path)
font = ImageFont.truetype("arial.ttf", font_size)
except IOError:
# Fallback to the default PIL font if the above fails
font = ImageFont.load_default()
# Get size of the text to be added
text_width, text_height = draw.textsize(watermark_text, font)
# Calculate position for the watermark (centered)
x = (original.width - text_width) / 2
y = (original.height - text_height) / 2
# Draw the watermark text on the transparent layer
draw.text((x, y), watermark_text, fill=(255, 255, 255, 128), font=font) # White color with transparency (alpha)
# Combine original image with watermark
watermarked = Image.alpha_composite(original.convert("RGBA"), txt)
# Save the resulting image
watermarked = watermarked.convert("RGB") # Convert back to "RGB" if you want to save as JPEG
watermarked.save(output_image_path, "JPEG")
# Example usage
add_watermark("input_image.jpg", "output_image.jpg", "Watermark Text")
Input and Output: The add_watermark function takes the path of the input image, the path for saving the output image, and the text of the watermark.
Load Image: It opens the original image in RGBA mode to handle transparency.
Transparent Layer: It creates a new transparent image where the watermark will be drawn.
Font Handling: It tries to load a TrueType font. If the specific font isn't found, it defaults to a basic font.
Calculate Position: It calculates the position to place the watermark text in the center of the image.
Draw Watermark: It draws the watermark text on the transparent layer.
Combine Images: The original image and the watermark are combined, and the result is saved.
fill parameter in the draw.text method to modify the color and transparency of the watermark.ImageFont.truetype is correct, or replace it with a valid font file on your system.Not yet included in a published release.