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

如何用Python PIL库在TIFF图片上生成清晰平滑的文字?

使用PIL给TIFF图片添加文字时文字质量差(像素缺失)的解决方法

问题描述

使用PIL打开TIFF图片并在右下角添加文字,功能已实现但文字质量极差:白色文字出现像素缺失,疑似Alpha通道被截断,即使设置Image.paste的mask参数也无改善。

环境:MacBook Pro Ventura 13.4.1、PIL 10.0.1、Python 3.8

原代码:

from PIL import Image as PILImage, ImageDraw, ImageFont
import math

padding = (10, 16)
img = PILImage.open('/path/to/tiff/image.tiff')
draw = ImageDraw.Draw(img)

text = 'Holi Moli, this looks terrible'
font = ImageFont.truetype('/path/to/font/FreeMono.ttf', 24)
text_img = PILImage.new('RGB', img.size, (255, 255, 255))
textImg = ImageDraw.Draw(text_img)

# get size of rendered text
bbox = draw.textbbox((0,0), text, font)
# calculate position of text background
bgX = img.width - padding[0] - bbox[2]
bgY = img.height - padding[1] - bbox[3]
textX = img.width - math.ceil(padding[0] * 0.5) - bbox[2]
textY = img.height - math.ceil( padding[1] * 0.5) - bbox[3]
draw.text(xy=(textX, textY), text=text, font=font, fill=(255, 255, 255, 0))

img.paste(im=draw._image, box=(0, 0), mask=draw._image)
img.show()

解决方法

问题已解决,核心注意两点:

  • 无需创建额外的绘图上下文(原代码中text_img和textImg属于冗余操作)
  • 文字渲染差的根源是使用了RGBA模式,切换为RGB模式后问题即可解决(暂未明确RGBA模式下Alpha通道异常的具体原因,但RGB模式可正常渲染文字)

优化后的示例代码:

from PIL import Image as PILImage, ImageDraw, ImageFont
import math

padding = (10, 16)
# 打开图片时指定转换为RGB模式
img = PILImage.open('/path/to/tiff/image.tiff').convert('RGB')
draw = ImageDraw.Draw(img)

text = 'Holi Moli, this looks great now!'
font = ImageFont.truetype('/path/to/font/FreeMono.ttf', 24)

# 获取文字尺寸
bbox = draw.textbbox((0,0), text, font)
# 计算右下角位置(调整padding)
textX = img.width - padding[0] - bbox[2]
textY = img.height - padding[1] - bbox[3]

# 直接在原图上绘制白色文字
draw.text(xy=(textX, textY), text=text, font=font, fill=(255, 255, 255))

img.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 16:24:57