用 PIL 在模板图上填数字,在本地Windows里看正常,但是部署在测试环境Ubuntu环境,出来的字特别小,把 font_size 从 24 调到 48 也没变化。
原因:
ImageFont.load_default() 在 Pillow 10.1.0 之前返回的是固定尺寸的位图字体,不接受 size 参数。
修复:
arial.ttf 从 C:\Windows\Fonts\ 拷一份放到脚本同级目录。
python
import os
from PIL import Image, ImageDraw, ImageFont
class ImageTextHandler:
def __init__(self, img_path):
self.img_path = img_path
self.img = Image.open(img_path)
self.draw = ImageDraw.Draw(self.img)
base = os.path.dirname(os.path.abspath(__file__))
try:
self.font = ImageFont.truetype(os.path.join(base, "arial.ttf"), 24)
except Exception as e:
print("字体加载失败,回退默认字体:", e)
self.font = ImageFont.load_default()
def replace_text(self, data, pos, color):
x1, y1, x2, y2 = pos
self.draw.rectangle([x1, y1, x2, y2], fill=(255, 255, 255))
self.draw.text((x1, y1), str(data), fill=color, font=self.font)
def save_img(self, img_path='output_with_bg.jpg'):
self.img.save(img_path)