You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PIL ImageDraw文本绘制问题:每2句下移100像素拼接错误排查

问题修复方案

问题根源

  1. 未清空result变量,导致后续内容持续累积,无法实现正确分段
  2. 计算文本宽度时误用单个句号的尺寸,导致文本居中位置错误
  3. 图片保存方法调用错误(image_save应为image.save)
  4. 未处理循环结束后剩余的句子(若句子总数为奇数时会遗漏)

修改后的代码

import PIL
from PIL import Image, ImageFont, ImageDraw
import textwrap

# 初始化字体与图片
font = ImageFont.truetype("arial.ttf", 36)
image = Image.open("testing1.jpg")
draw = ImageDraw.Draw(image)

texts = "We are having a long, long very long sentence here. Just trying to test if it works. We are trying to test. Testing we do all day all day. All day. Long."
image_width, image_height = image.size
y_text = 600

period_count = 0
temp_list = []

for char in texts:
    temp_list.append(char)
    if char == ".":
        period_count += 1
        # 每2个句子处理一次
        if period_count % 2 == 0:
            current_text = "".join(temp_list)
            # 自动换行适配图片宽度
            wrapped_text = textwrap.fill(current_text, width=40)
            # 获取多行文本的整体尺寸
            text_width, text_height = draw.textsize(wrapped_text, font=font)
            # 计算居中位置
            x_pos = (image_width - text_width) / 2
            # 绘制文本
            draw.text((x_pos, y_text), wrapped_text, font=font, fill=(200, 200, 200))
            # 下移位置:文本高度 + 额外100像素间距
            y_text += text_height + 100
            # 清空临时列表,准备下一组句子
            temp_list = []

# 处理剩余的句子(如果句子总数是奇数)
if temp_list:
    remaining_text = "".join(temp_list)
    wrapped_remaining = textwrap.fill(remaining_text, width=40)
    text_width, text_height = draw.textsize(wrapped_remaining, font=font)
    x_pos = (image_width - text_width) / 2
    draw.text((x_pos, y_text), wrapped_remaining, font=font, fill=(200, 200, 200))

# 保存图片
image.save("testing12.jpeg")

关键修改点

  • 移除累积内容的result变量,改用current_text仅存储当前要处理的2个句子
  • 用draw.textsize(wrapped_text, font=font)获取多行文本真实尺寸,确保居中位置正确
  • 修正图片保存方法为image.save()
  • 添加剩余句子处理逻辑,避免遗漏最后一组不足2个的句子
  • 优化变量命名(如l改为char),提升代码可读性

内容的提问来源于stack exchange,提问作者mnnewbilr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 20:05:30