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

Python Pillow/PIL库添加文字分辨率低/模糊问题求助

解决Pillow添加文字模糊的问题

常见原因及修复方案

1. 字体尺寸与图像分辨率不匹配

你代码里字体设为15号,如果原背景图分辨率较高,15号字实际显示会很小,放大后自然模糊。需要根据图像像素尺寸调整字体大小:

  • 先查看图像像素尺寸:
im = Image.open("quotes-background.png")
print(im.size)  # 输出格式:(宽度, 高度)
  • 根据画布大小调整字号,比如画布宽度为1920像素时,字号可设为30-40左右,保证文字显示清晰。

2. 启用文字抗锯齿

Pillow绘制文字时,默认抗锯齿效果可能不足,可通过参数优化:

  • 若使用Pillow 9.1.0及以上版本,直接在text方法中添加antialias=True开启抗锯齿:
d1.text((60, 200), text.title(), fill='yellow', font=font, antialias=True)

3. 优化图片保存参数

保存PNG时避免压缩过度,设置optimize=True和quality=9(PNG的quality参数控制压缩级别,9为最高质量):

im.save('quotes.png', optimize=True, quality=9)

4. 高分辨率画布绘制后缩放(可选)

如果需要在低分辨率画布上显示清晰文字,可先在2-4倍尺寸的画布上绘制,再缩小到目标尺寸:

scale = 2
im = Image.open("quotes-background.png")
# 创建高分辨率画布
high_res_im = im.resize((im.width*scale, im.height*scale), Image.Resampling.LANCZOS)
# 对应放大字号
font = ImageFont.truetype('Poppins-Bold.ttf', 15*scale )
d1 = ImageDraw.Draw(high_res_im)
d1.text((60*scale, 200*scale), text.title(), fill='yellow', font=font, antialias=True)
# 缩小回原尺寸
final_im = high_res_im.resize(im.size, Image.Resampling.LANCZOS)
final_im.save('quotes.png', optimize=True, quality=9)

调整后的完整代码示例

from PIL import Image, ImageDraw, ImageFont

text = 'Any fool can write code that a computer can understand. \nGood programmers write code that humans can understand.'
# 根据图像尺寸调整字号(示例设为36号)
font = ImageFont.truetype('Poppins-Bold.ttf', 36 )
im = Image.open("quotes-background.png")
d1 = ImageDraw.Draw(im)
# 开启抗锯齿绘制文字
d1.text((60 , 200), text.title(), fill='yellow', font=font, antialias=True)
# 高质量保存图片
im.save('quotes.png', optimize=True, quality=9)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 00:50:35