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

在PIL图像上绘制文本时出现棋盘格图案问题排查

问题:PIL写入文本出现棋盘格而非预期内容

问题现象

使用PIL库向图像写入文本时,目标位置未显示预期的文本内容,反而出现棋盘格图案。

相关代码

font_size = 18
num_lines_possible = h // font_size # height of the bounding box i want to write the text to
for j in range(min(len(lines), num_lines_possible)):
        print(f"lines[j]: {lines[j]}")
        button_draw.text((0, j * font_size), lines[j], font=font_style, fill=t_color)

使用的字体列表

fonts = [ImageFont.truetype('/System/Library/Fonts/SFCompact.ttf', size=16), 
         ImageFont.truetype('/System/Library/Fonts/Supplemental/Verdana Bold.ttf', size=16),
         ImageFont.truetype('/System/Library/Fonts/Avenir.ttc', size=16),
         ImageFont.truetype('/System/Library/Fonts/Helvetica.ttc', size=16),
         ImageFont.truetype('/System/Library/Fonts/SFArabic.ttf', size=16)]

预期显示的调试文本内容

lines[j]: Bias-Variance Trade-off:
lines[j]: • For a given x, we have a conditional
lines[j]: p(y|x) of sales prices; the Bayesian
lines[j]: prediction of the label value for a
lines[j]: x is Ey[y|x]; • The noise term
lines[j]: the inherent variance in labels y � x �
lines[j]: [Ey[y|x] − y]2p(x, y)dxdy � �� � noise:
lines[j]: due to randomness of y • This term has
lines[j]: to do with our prediction hD(x) x,
lines[j]: Our hammer: Maximum likelihood estimation Optimization
lines[j]: (π∗ c , θ∗ ck) = arg max  � n log πyn + � n,k xnk log θynk  
lines[j]: θ∗ ck = #of times word k shows up in data points labeled as c
lines[j]: trials for data points labeled as c π∗ c = #of data points labeled as
lines[j]: Estimating {θck, k = 1, 2, · · · , K} We want to maximize � n:yn=c,k xnk
lines[j]: θck Intuition • Again similar to roll a dice: each side of the dice shows
lines[j]: with a probability of θck (total K sides) • And we have total � n:yn=c,k
slide_title: HnjRKOMBUYeHrZeGxPCjwg

问题原因分析

  • 字体大小不匹配:代码中计算行高用的是font_size = 18,但初始化字体时设置的是size=16,行间距计算错误导致文本行重叠或超出绘制区域,引发渲染异常。
  • 特殊字符渲染失败:预期文本包含大量数学符号(如∗、∑、−等),部分字体(比如SFArabic.ttf这类阿拉伯语字体)无法识别这些字符,会用棋盘格作为缺失字符的占位符。
  • .ttc字体加载异常:Avenir.ttc、Helvetica.ttc是字体集合文件,加载时未指定具体字体索引(通过index参数),可能加载到不支持当前文本的字体,导致渲染出错。
  • 绘制区域超出图像边界:如果变量h(目标绘制区域高度)计算错误,或图像本身高度不足以容纳所有文本行,超出边界的文本渲染会出现异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 06:46:22