编程怎么在图片上加文字

时间:2025-03-05 15:07:36 游戏攻略

要在图片上添加文字,您可以使用多种方法,包括使用命令行工具、图像编辑软件或编程语言。以下是几种常见的方法:

使用命令行工具

您可以使用Python的PIL库(Pillow)来创建一个脚本,该脚本可以在命令行中运行,并允许您输入文字、大小、透明度和位置。以下是一个简单的示例代码:

```python

from PIL import Image, ImageDraw, ImageFont

import os

def get_position(image_width, image_height, text_width, text_height, position_id=9, margin=10):

"""获取文字位置, position_id 1: 左上, 2: 中上, 3: 右上 4: 中左, 5: 正中, 6: 中右 7: 左下, 8: 下中, 9: 右下"""

if position_id == 1:

x = margin

y = margin

elif position_id == 2:

x = (image_width - text_width) / 2 + margin

y = margin

elif position_id == 3:

x = image_width - text_width - margin

y = margin

elif position_id == 4:

x = margin

y = (image_height - text_height) / 2 + margin

elif position_id == 5:

x = (image_width - text_width) / 2 + margin

y = (image_height - text_height) / 2 + margin

elif position_id == 6:

x = image_width - text_width - margin

y = (image_height - text_height) / 2 + margin

elif position_id == 7:

x = margin

y = image_height - text_height - margin

elif position_id == 8:

x = (image_width - text_width) / 2 + margin

y = image_height - text_height - margin

elif position_id == 9:

x = image_width - text_width - margin

y = image_height - text_height - margin

else:

raise ValueError("Invalid position_id")

return x, y

获取用户输入

text = input("请输入水印文字: ")

text_size = int(input("请输入文字大小 (默认20px): "))

opacity = float(input("请输入透明度 (默认50%): "))

position_id = int(input("请输入文字位置 (1-9): "))

加载图片

image_path = "path/to/your/image.png"

image = Image.open(image_path)

draw = ImageDraw.Draw(image)

设置字体

font_path = "path/to/your/font.ttf"

font = ImageFont.truetype(font_path, size=text_size)

计算文字位置

text_width, text_height = draw.textsize(text, font=font)

x, y = get_position(image.width, image.height, text_width, text_height, position_id)

添加文字

draw.text((x, y), text, font=font, fill='white' if opacity < 1 else 'black')

保存图片

output_path = "path/to/your/watermark.png"

image.save(output_path)

```

使用图像编辑软件

您可以使用像Adobe Photoshop、GIMP或在线工具(如Canva)来添加文字。这些工具通常提供直观的界面,允许您选择字体、大小、颜色和位置,并预览效果。

使用编程语言

除了上述命令行方法外,您还可以使用Python的PIL库(Pillow)或其他编程语言(如JavaScript的Canvas API)来在图片上添加文字。以下是一个使用JavaScript和Canvas API的简单示例: