Created
February 15, 2025 07:15
-
-
Save RibomBalt/b508e3643598e37ac74b36d108676a4a to your computer and use it in GitHub Desktop.
Create auto label/watermark for images with cairosvg
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
import argparse | |
from PIL import Image | |
import cairosvg | |
import os | |
import base64 | |
def add_watermark(image_path, text, x, y, output_path): | |
""" | |
在图片左上角添加水印文字 | |
:param image_path: 输入图片路径 | |
:param text: 水印文字 | |
:param x: 水印x坐标(像素或百分比,例如"10%"或"100px") | |
:param y: 水印y坐标(像素或百分比) | |
:param output_path: 输出图片路径 | |
""" | |
with Image.open(image_path) as img: | |
width, height = img.size | |
# # 处理x坐标 | |
# if x.endswith('%'): | |
# x_val = int(float(x[:-1]) / 100 * width) | |
# else: | |
# x_val = int(x[:-2]) # 移除"px" | |
# # 处理y坐标 | |
# if y.endswith('%'): | |
# y_val = int(float(y[:-1]) / 100 * height) | |
# else: | |
# y_val = int(y[:-2]) # 移除"px" | |
x_val = x | |
y_val = y | |
with open(image_path, 'rb') as fp: | |
content = fp.read() | |
content_b64 = base64.b64encode(content).decode('utf-8') | |
image_dataurl = f"data:image/png;base64,{content_b64}" | |
# 创建SVG并添加水印 | |
svg_code = f""" | |
<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}"> | |
<image href="{image_dataurl}" x="0" y="0" width="{width}" height="{height}"/> | |
<text x="{x_val}" y="{y_val}" font-size="10em" fill="rgba(0, 0, 0, 0.8)"> | |
{text} | |
</text> | |
</svg> | |
""" | |
# 将SVG转换为PNG | |
cairosvg.svg2png(bytestring=svg_code.encode(), write_to=output_path) | |
print(f"成功添加水印,输出路径: {output_path}") | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser(description='图片水印工具') | |
parser.add_argument('-i', '--input', type=str, required=True, help='输入图片路径') | |
parser.add_argument('-t', '--text', type=str, required=True, help='水印文字内容') | |
parser.add_argument('-s', '--size', type=str, default='5em', help='水印文字大小') | |
parser.add_argument('-x', type=str, default='10px', help='水印x坐标(以px或%结尾,例如"10px"或"10%")') | |
parser.add_argument('-y', type=str, default='10px', help='水印y坐标(以px或%结尾,例如"10px"或"10%")') | |
parser.add_argument('-o', '--output', type=str, default='output.png', help='输出图片路径') | |
args = parser.parse_args() | |
add_watermark(args.input, args.text, args.x, args.y, args.output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment