|
发表于 2024-12-24 11:02:56
|
显示全部楼层
看起来你使用了 Pillow 版本中没有 `textsize` 方法。较新的 Pillow 版本将 `textsize` 方法改为了 `textbbox` 来获取文本大小。试试使用以下代码:
- from PIL import Image, ImageDraw, ImageFont
- def create_image_with_text(text, image_path, output_path):
- # 打开自定义图片
- image = Image.open(image_path)
- draw = ImageDraw.Draw(image)
-
- # 使用自定义字体和大小(你需要一个 .ttf 字体文件)
- font = ImageFont.truetype("arial.ttf", 40)
-
- # 获取文本大小
- text_width, text_height = draw.textbbox((0, 0), text, font=font)[2:]
-
- # 计算文本在图片中居中的位置
- width, height = image.size
- text_x = (width - text_width) / 2
- text_y = (height - text_height) / 2
-
- # 添加文本到图片
- draw.text((text_x, text_y), text, font=font, fill="black")
-
- # 保存输出图片
- image.save(output_path)
- # 示例使用
- create_image_with_text("FishC", "input_image.jpg", "output_image.jpg")
复制代码
请确保你的环境中安装了 Pillow,并且提供了一个有效的字体文件路径。例如,“arial.ttf”为系统默认字体,可以替换为其他字体路径。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|