Python Watermark Image: Step-by-Step Guide

Python can utilize the Pillow library to add watermarks to images. Here is an example code:

from PIL import Image, ImageDraw, ImageFont

def add_watermark(image_path, watermark_text, output_path):
    # 打开图片
    image = Image.open(image_path)

    # 创建绘图对象
    draw = ImageDraw.Draw(image)

    # 设置水印文本的字体和大小
    font = ImageFont.truetype('arial.ttf', 36)

    # 计算水印文本的位置
    text_width, text_height = draw.textsize(watermark_text, font)
    x = image.width - text_width - 10
    y = image.height - text_height - 10

    # 添加水印文本
    draw.text((x, y), watermark_text, font=font, fill=(255, 255, 255, 128))

    # 保存图片
    image.save(output_path)

# 示例用法
add_watermark('input.jpg', 'Watermark', 'output.jpg')

In the above code, first open the image to which the watermark will be added using the Image.open() method, then create a drawing object draw. Next, use the textsize() method from the ImageDraw library to calculate the size of the watermark text, and calculate the position of the watermark text based on the image size and watermark text size. Finally, use the draw.text() method to add the watermark text and save the image with the watermark using image.save().

bannerAds