Pillow绘制文字到图片上如何设置字体大小样式避免乱码

引言:Pillow文字绘制的核心挑战
在使用Python的Pillow库(PIL)向图片上绘制文字时,开发者经常会遇到两个主要问题:如何精确控制字体的大小和样式,以及如何避免中文或其他非ASCII字符显示为乱码。这些问题看似简单,但背后涉及字体文件的选择、编码处理、以及渲染引擎的工作原理。本文将深入探讨这些技术细节,并提供完整的解决方案。
为什么会出现乱码问题?
乱码的根本原因在于Pillow默认使用的是
位图字体
(Bitmap Font),这种字体只包含ASCII字符集(0-127),无法处理中文、日文、韩文等Unicode字符。当尝试绘制中文时,Pillow会fallback到默认字体,导致字符无法正确显示,最终呈现为方框或问号。
1. 理解Pillow的字体系统
1.1 Pillow支持的字体类型
Pillow支持三种主要的字体处理方式:
位图字体(BitmapFont)
:默认字体,仅支持ASCII
TrueType字体(ImageFont.truetype)
:支持完整的Unicode字符集
OpenType字体
:与TrueType类似,功能更强大
1.2 字体加载的核心API
from PIL import Image, ImageDraw, ImageFont
import os

# 核心API概览
# 1. ImageFont.load_default() – 加载默认位图字体
# 2. ImageFont.truetype(font_path, size) – 加载TrueType字体
# 3. ImageFont.load_path(font_filename) – 从系统路径加载字体
2. 解决乱码问题:正确加载字体
2.1 为什么必须使用TrueType字体
TrueType字体(.ttf文件)是解决乱码的关键。它们包含完整的Unicode字符映射表,能够正确渲染各种语言的字符。
2.2 获取中文字体文件
在不同操作系统中,中文字体的位置:
Windows
:
C:\Windows\Fonts\
目录下
常见中文字体:
simsun.ttc
(宋体)、
msyh.ttc
(微软雅黑)
macOS
:
/System/Library/Fonts/
或
/Library/Fonts/
常见中文字体:
PingFang.ttc
(苹方)、
Songti.ttc
(宋体)
Linux
:
/usr/share/fonts/
或
~/.fonts/
常见中文字体:
wqy-zenhei.ttc
(文泉驿正黑)
2.3 完整的字体加载代码示例
from PIL import Image, ImageDraw, ImageFont
import os

def load_chinese_font(preferred_size=36):
“””
跨平台加载中文字体的完整解决方案
“””
# 1. 首先尝试加载系统中文字体
font_paths = []

# Windows系统字体路径
if os.name == ‘nt’:
windows_fonts = [
r’C:\Windows\Fonts\simsun.ttc’, # 宋体
r’C:\Windows\Fonts\msyh.ttc’, # 微软雅黑
r’C:\Windows\Fonts\simhei.ttc’, # 黑体
]
font_paths.extend(windows_fonts)

# macOS系统字体路径
elif os.name == ‘posix’:
mac_fonts = [
‘/System/Library/Fonts/PingFang.ttc’, # 苹方
‘/System/Library/Fonts/STSong.ttc’, # 华文宋体
‘/Library/Fonts/Arial Unicode.ttf’, # 通用Unicode字体
]
font_paths.extend(mac_fonts)

# Linux系统字体路径
linux_fonts = [
‘/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc’, # 文泉驿正黑
‘/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc’,
‘~/.fonts/wqy-zenhei.ttc’,
]
font_paths.extend(linux_fonts)

# 2. 如果系统字体不存在,使用默认字体(但无法显示中文)
# 这种情况下建议用户手动下载中文字体
font = None
for path in font_paths:
expanded_path = os.path.expanduser(path)
if os.path.exists(expanded_path):
try:
font = ImageFont.truetype(expanded_path, preferred_size)
print(f”成功加载字体: {expanded_path}”)
return font
except Exception as e:
print(f”加载字体失败 {expanded_path}: {e}”)
continue

# 3. 如果所有系统字体都不存在,使用默认字体(会乱码)
print(“警告: 未找到中文字体,将使用默认字体(无法显示中文)”)
return ImageFont.load_default()

# 使用示例
font = load_chinese_font(48)
3. 字体大小和样式的精确控制
3.1 字体大小设置
字体大小通过
ImageFont.truetype()
的第二个参数控制,单位是
像素
。
# 不同大小的字体
small_font = ImageFont.truetype(“simsun.ttc”, 16)
medium_font = ImageFont.truetype(“simsun.ttc”, 32)
large_font = ImageFont.truetype(“simsun.ttc”, 72)

# 动态计算字体大小
def calculate_font_size(text, max_width, initial_size=48, font_path=”simsun.ttc”):
“””
自动调整字体大小以适应指定宽度
“””
font = ImageFont.truetype(font_path, initial_size)
bbox = font.getbbox(text)
text_width = bbox[2] – bbox[0]

if text_width > max_width:
# 按比例缩小
scale = max_width / text_width
new_size = int(initial_size * scale)
return ImageFont.truetype(font_path, new_size)
return font

# 使用示例
text = “这是一段很长的中文文本”
font = calculate_font_size(text, max_width=200, initial_size=48)
3.2 字体样式控制
TrueType字体支持多种样式,但Pillow本身不直接提供粗体/斜体切换。需要通过以下方式实现:
方法1:使用字体文件的不同变体
# 使用不同的字体文件实现样式
styles = {
‘normal’: ‘simsun.ttc’, # 宋体(常规)
‘bold’: ‘simhei.ttc’, # 黑体(粗体)
‘italic’: ‘kaiiti.ttf’, # 楷体(斜体)
‘bold_italic’: ‘simyou.ttc’ # 幼圆(粗斜体)
}

def get_font_with_style(style_name, size=32):
“””根据样式名称获取字体”””
font_file = styles.get(style_name, ‘simsun.ttc’)
return ImageFont.truetype(font_file, size)

# 使用示例
bold_font = get_font_with_style(‘bold’, 36)
方法2:通过图像处理模拟粗体效果
def create_bold_text_effect(draw, position, text, font, fill_color=”black”):
“””
通过多次绘制模拟粗体效果
“””
x, y = position
# 绘制多个偏移版本
offsets = [(0, 1), (1, 0), (1, 1), (-1, 0), (0, -1)]
for dx, dy in offsets:
draw.text((x + dx, y + dy), text, font=font, fill=fill_color)
# 最后绘制中心文字
draw.text((x, y), text, font=font, fill=fill_color)

# 使用示例
img = Image.new(‘RGB’, (400, 200), color=’white’)
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(“simsun.ttc”, 48)
create_bold_text_effect(draw, (50, 50), “粗体效果”, font)
img.save(‘bold_text.png’)
3.3 字体颜色和透明度控制
# 基本颜色设置
draw.text((10, 10), “红色文字”, font=font, fill=(255, 0, 0))

# RGBA颜色(支持透明度)
draw.text((10, 50), “半透明文字”, font=font, fill=(255, 0, 0, 128))

# 创建带阴影的文字
def draw_text_with_shadow(draw, position, text, font, text_color=”white”, shadow_color=”black”, offset=(2, 2)):
“””绘制带阴影的文字”””
x, y = position
# 先绘制阴影
draw.text((x + offset[0], y + offset[1]), text, font=font, fill=shadow_color)
# 再绘制主文字
draw.text((x, y), text, font=font, fill=text_color)

# 使用示例
draw_text_with_shadow(draw, (50, 100), “阴影文字”, font)
4. 高级文字布局和多行文本处理
4.1 自动换行处理
def draw_multiline_text(draw, text, position, font, max_width, line_spacing=1.2, **kwargs):
“””
自动换行绘制多行文本
“””
x, y = position
line_height = font.getbbox(‘A’)[3] * line_spacing # 使用字母’A’计算行高
words = text.split(‘ ‘)
lines = []
current_line = []

for word in words:
# 检查当前行加上新词后的宽度
test_line = ‘ ‘.join(current_line + [word])
bbox = font.getbbox(test_line)
if bbox[2] – bbox[0] <= max_width: current_line.append(word) else: if current_line: lines.append(' '.join(current_line)) current_line = [word] if current_line: lines.append(' '.join(current_line)) # 绘制每一行 for i, line in enumerate(lines): draw.text((x, y + i * line_height), line, font=font, **kwargs) return len(lines) * line_height # 使用示例 long_text = "这是一个很长的中文句子,需要自动换行来适应图片的宽度限制。" img = Image.new('RGB', (400, 200), color='white') draw = ImageDraw.Draw(img) font = ImageFont.truetype("simsun.ttc", 24) draw_multiline_text(draw, long_text, (10, 10), font, max_width=380) img.save('multiline_text.png') 4.2 文字居中对齐 def draw_centered_text(draw, text, position, font, **kwargs): """ 绘制水平居中的文字 """ bbox = font.getbbox(text) text_width = bbox[2] - bbox[0] text_height = bbox[3] - bbox[1] x = position[0] - text_width // 2 y = position[1] - text_height // 2 draw.text((x, y), text, font=font, **kwargs) def draw_centered_multiline_text(draw, text, box_position, box_size, font, line_spacing=1.2, **kwargs): """ 在指定区域内绘制居中的多行文本 """ box_x, box_y = box_position box_w, box_h = box_size # 计算行数和行高 lines = text.split('\n') line_height = font.getbbox('A')[3] * line_spacing # 计算总高度 total_height = len(lines) * line_height # 计算起始Y坐标(垂直居中) start_y = box_y + (box_h - total_height) // 2 # 绘制每一行(水平居中) for i, line in enumerate(lines): bbox = font.getbbox(line) text_width = bbox[2] - bbox[0] x = box_x + (box_w - text_width) // 2 y = start_y + i * line_height draw.text((x, y), line, font=font, **kwargs) # 使用示例 img = Image.new('RGB', (400, 200), color='lightblue') draw = ImageDraw.Draw(img) font = ImageFont.truetype("simsun.ttc", 32) draw_centered_multiline_text(draw, "居中\n多行\n文本", (50, 20), (300, 160), font) img.save('centered_text.png') 5. 完整项目示例:生成带文字的图片 5.1 项目结构设计 from PIL import Image, ImageDraw, ImageFont import os from typing import Tuple, Optional class TextOnImageGenerator: """ 专业的文字图片生成器,解决乱码问题并提供丰富的文字样式 """ def __init__(self, width=800, height=600, background_color=(255, 255, 255)): self.width = width self.height = height self.background_color = background_color self.image = Image.new('RGB', (width, height), background_color) self.draw = ImageDraw.Draw(self.image) self.font_cache = {} def get_font(self, font_size=36, font_style='normal', font_path=None): """ 智能字体加载,支持缓存和样式 """ cache_key = f"{font_size}_{font_style}_{font_path}" if cache_key in self.font_cache: return self.font_cache[cache_key] # 如果没有指定字体路径,自动查找系统中文字体 if font_path is None: font_path = self._find_chinese_font() try: font = ImageFont.truetype(font_path, font_size) self.font_cache[cache_key] = font return font except Exception as e: print(f"加载字体失败: {e}") # 降级到默认字体(会乱码) return ImageFont.load_default() def _find_chinese_font(self): """ 自动查找系统中文字体 """ font_candidates = [] if os.name == 'nt': # Windows font_candidates = [ r'C:\Windows\Fonts\simsun.ttc', r'C:\Windows\Fonts\msyh.ttc', r'C:\Windows\Fonts\simhei.ttc', ] elif os.name == 'posix': # macOS/Linux font_candidates = [ '/System/Library/Fonts/PingFang.ttc', '/System/Library/Fonts/STSong.ttc', '/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc', '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc', ] for path in font_candidates: if os.path.exists(path): return path # 如果找不到,提示用户 raise FileNotFoundError( "未找到中文字体文件。请手动下载中文字体(如simsun.ttc)并指定路径。" ) def add_text(self, text, position, font_size=36, font_style='normal', fill=(0, 0, 0), align='left', max_width=None, line_spacing=1.2, shadow=False, shadow_offset=(2, 2), shadow_color=(0, 0, 0)): """ 添加文字到图片 """ font = self.get_font(font_size, font_style) # 处理自动换行 if max_width: return self._draw_wrapped_text( text, position, font, max_width, fill, line_spacing, shadow, shadow_offset, shadow_color ) else: # 简单绘制 if shadow: self._draw_text_with_shadow(position, text, font, fill, shadow_offset, shadow_color) else: self.draw.text(position, text, font=font, fill=fill) return font.getbbox(text) def _draw_wrapped_text(self, text, position, font, max_width, fill, line_spacing, shadow, shadow_offset, shadow_color): """ 绘制自动换行的文字 """ x, y = position line_height = font.getbbox('A')[3] * line_spacing # 简单的按字符换行(中文需要按字符处理) lines = [] current_line = "" for char in text: test_line = current_line + char bbox = font.getbbox(test_line) if bbox[2] - bbox[0] <= max_width: current_line = test_line else: if current_line: lines.append(current_line) current_line = char if current_line: lines.append(current_line) # 绘制每一行 for i, line in enumerate(lines): line_y = y + i * line_height if shadow: self._draw_text_with_shadow((x, line_y), line, font, fill, shadow_offset, shadow_color) else: self.draw.text((x, line_y), line, font=font, fill=fill) return (x, y, x + max_width, y + len(lines) * line_height) def _draw_text_with_shadow(self, position, text, font, fill, shadow_offset, shadow_color): """绘制带阴影的文字""" x, y = position dx, dy = shadow_offset self.draw.text((x + dx, y + dy), text, font=font, fill=shadow_color) self.draw.text((x, y), text, font=font, fill=fill) def save(self, filename): """保存图片""" self.image.save(filename) print(f"图片已保存到: {filename}") # 完整使用示例 def main(): # 创建生成器 generator = TextOnImageGenerator(width=800, height=600, background_color=(240, 240, 240)) # 添加标题(大字体,带阴影) generator.add_text( "Pillow文字绘制示例", position=(400, 50), font_size=48, fill=(30, 30, 30), shadow=True, shadow_offset=(3, 3), shadow_color=(200, 200, 200) ) # 添加副标题(中等字体) generator.add_text( "解决中文乱码问题", position=(400, 120), font_size=32, fill=(80, 80, 80) ) # 添加多行正文(自动换行) long_text = "这是一个完整的Pillow文字绘制示例,展示了如何正确加载中文字体、设置字体大小和样式,以及避免乱码问题。通过使用TrueType字体文件,我们可以完美支持中文、日文、韩文等Unicode字符。" generator.add_text( long_text, position=(50, 180), font_size=24, fill=(50, 50, 50), max_width=700, line_spacing=1.5 ) # 添加带样式的文字 generator.add_text( "粗体效果示例", position=(50, 350), font_size=36, font_style='bold', fill=(200, 0, 0) ) # 添加多语言测试 generator.add_text( "中文 English 日本語 한국어", position=(50, 420), font_size=28, fill=(0, 100, 0) ) # 保存最终图片 generator.save('pillow_text_example.png') if __name__ == '__main__': main() 6. 常见问题排查和最佳实践 6.1 乱码问题排查清单 def debug_font_issue(text): """ 调试字体问题的诊断函数 """ print("=== 字体问题诊断 ===") print(f"1. 测试文本: {text}") print(f"2. 文本编码: {text.encode('utf-8')}") print(f"3. 字符类型: {[type(c) for c in text]}") # 检查是否包含中文字符 has_chinese = any('\u4e00' <= c <= '\u9fff' for c in text) print(f"4. 包含中文: {has_chinese}") # 尝试加载字体 try: font = ImageFont.truetype("simsun.ttc", 32) print("5. 字体加载: 成功") # 测试字体渲染 bbox = font.getbbox(text) print(f"6. 文字尺寸: {bbox}") except Exception as e: print(f"5. 字体加载: 失败 - {e}") print("6. 建议: 下载中文字体文件并指定正确路径") # 使用示例 debug_font_issue("测试中文") 6.2 性能优化建议 # 1. 字体缓存:避免重复加载相同字体 font_cache = {} def get_font_cached(font_path, size): key = (font_path, size) if key not in font_cache: font_cache[key] = ImageFont.truetype(font_path, size) return font_cache[key] # 2. 批量绘制:减少ImageDraw对象创建 def batch_draw_texts(image, texts_with_styles): """ 批量绘制多个文字,提高性能 """ draw = ImageDraw.Draw(image) for item in texts_with_styles: font = get_font_cached(item['font_path'], item['size']) draw.text(item['position'], item['text'], font=font, fill=item['color']) return image # 3. 使用textbbox替代getbbox(Pillow 9.2.0+) # 新版本推荐使用textbbox,它返回更精确的边界框 def get_text_dimensions(text, font): """获取文字尺寸(推荐方式)""" try: # Pillow 9.2.0+ bbox = font.getbbox(text) # 或 font.getbbox(text) return bbox[2] - bbox[0], bbox[3] - bbox[1] except: # 旧版本兼容 return font.getsize(text) 6.3 跨平台部署注意事项 def deployable_font_loader(font_filename="simsun.ttc"): """ 部署时的字体加载策略 """ # 1. 优先使用相对路径的字体文件(推荐) local_font = os.path.join("fonts", font_filename) if os.path.exists(local_font): return local_font # 2. 其次使用环境变量指定的路径 env_font = os.environ.get("CUSTOM_FONT_PATH") if env_font and os.path.exists(env_font): return env_font # 3. 最后尝试系统字体 system_fonts = { 'nt': [r'C:\Windows\Fonts\simsun.ttc'], 'posix': ['/System/Library/Fonts/PingFang.ttc', '/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc'] } for path in system_fonts.get(os.name, []): if os.path.exists(path): return path raise FileNotFoundError("找不到字体文件,请将字体文件放在./fonts/目录或设置CUSTOM_FONT_PATH环境变量") # Docker部署示例 """ Dockerfile中添加字体: RUN apt-get update && apt-get install -y fonts-wqy-zenhei COPY fonts/simsun.ttc /usr/local/share/fonts/ """ 7. 总结 通过本文的详细讲解,您应该已经掌握了使用Pillow绘制文字时的核心要点: 必须使用TrueType字体 :这是避免乱码的唯一方法 正确加载字体 :跨平台查找系统字体或使用本地字体文件 精确控制样式 :通过字体文件和图像处理实现各种效果 高级布局 :处理自动换行、居中对齐等复杂需求 性能优化 :缓存字体、批量处理等最佳实践 记住, 字体文件是关键 。在生产环境中,建议将字体文件与代码一起部署,避免依赖系统字体。这样可以确保在任何环境下都能正确显示中文,彻底解决乱码问题。 # Pillow绘制文字到图片上如何设置字体大小样式避免乱码 引言:Pillow文字绘制的核心挑战 在使用Python的Pillow库(PIL)向图片上绘制文字时,开发者经常会遇到两个主要问题:如何精确控制字体的大小和样式,以及如何避免中文或其他非ASCII字符显示为乱码。这些问题看似简单,但背后涉及字体文件的选择、编码处理、以及渲染引擎的工作原理。本文将深入探讨这些技术细节,并提供完整的解决方案。 为什么会出现乱码问题? 乱码的根本原因在于Pillow默认使用的是 位图字体 (Bitmap Font),这种字体只包含ASCII字符集(0-127),无法处理中文、日文、韩文等Unicode字符。当尝试绘制中文时,Pillow会fallback到默认字体,导致字符无法正确显示,最终呈现为方框或问号。 1. 理解Pillow的字体系统 1.1 Pillow支持的字体类型 Pillow支持三种主要的字体处理方式: 位图字体(BitmapFont) :默认字体,仅支持ASCII TrueType字体(ImageFont.truetype) :支持完整的Unicode字符集 OpenType字体 :与TrueType类似,功能更强大 1.2 字体加载的核心API from PIL import Image, ImageDraw, ImageFont import os # 核心API概览 # 1. ImageFont.load_default() - 加载默认位图字体 # 2. ImageFont.truetype(font_path, size) - 加载TrueType字体 # 3. ImageFont.load_path(font_filename) - 从系统路径加载字体 2. 解决乱码问题:正确加载字体 2.1 为什么必须使用TrueType字体 TrueType字体(.ttf文件)是解决乱码的关键。它们包含完整的Unicode字符映射表,能够正确渲染各种语言的字符。 2.2 获取中文字体文件 在不同操作系统中,中文字体的位置: Windows : C:\Windows\Fonts\ 目录下 常见中文字体: simsun.ttc (宋体)、 msyh.ttc (微软雅黑) macOS : /System/Library/Fonts/ 或 /Library/Fonts/ 常见中文字体: PingFang.ttc (苹方)、 Songti.ttc (宋体) Linux : /usr/share/fonts/ 或 ~/.fonts/ 常见中文字体: wqy-zenhei.ttc (文泉驿正黑) 2.3 完整的字体加载代码示例 from PIL import Image, ImageDraw, ImageFont import os def load_chinese_font(preferred_size=36): """ 跨平台加载中文字体的完整解决方案 """ # 1. 首先尝试加载系统中文字体 font_paths = [] # Windows系统字体路径 if os.name == 'nt': windows_fonts = [ r'C:\Windows\Fonts\simsun.ttc', # 宋体 r'C:\Windows\Fonts\msyh.ttc', # 微软雅黑 r'C:\Windows\Fonts\simhei.ttc', # 黑体 ] font_paths.extend(windows_fonts) # macOS系统字体路径 elif os.name == 'posix': mac_fonts = [ '/System/Library/Fonts/PingFang.ttc', # 苹方 '/System/Library/Fonts/STSong.ttc', # 华文宋体 '/Library/Fonts/Arial Unicode.ttf', # 通用Unicode字体 ] font_paths.extend(mac_fonts) # Linux系统字体路径 linux_fonts = [ '/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc', # 文泉驿正黑 '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc', '~/.fonts/wqy-zenhei.ttc', ] font_paths.extend(linux_fonts) # 2. 如果系统字体不存在,使用默认字体(但无法显示中文) # 这种情况下建议用户手动下载中文字体 font = None for path in font_paths: expanded_path = os.path.expanduser(path) if os.path.exists(expanded_path): try: font = ImageFont.truetype(expanded_path, preferred_size) print(f"成功加载字体: {expanded_path}") return font except Exception as e: print(f"加载字体失败 {expanded_path}: {e}") continue # 3. 如果所有系统字体都不存在,使用默认字体(会乱码) print("警告: 未找到中文字体,将使用默认字体(无法显示中文)") return ImageFont.load_default() # 使用示例 font = load_chinese_font(48) 3. 字体大小和样式的精确控制 3.1 字体大小设置 字体大小通过 ImageFont.truetype() 的第二个参数控制,单位是 像素 。 # 不同大小的字体 small_font = ImageFont.truetype("simsun.ttc", 16) medium_font = ImageFont.truetype("simsun.ttc", 32) large_font = ImageFont.truetype("simsun.ttc", 72) # 动态计算字体大小 def calculate_font_size(text, max_width, initial_size=48, font_path="simsun.ttc"): """ 自动调整字体大小以适应指定宽度 """ font = ImageFont.truetype(font_path, initial_size) bbox = font.getbbox(text) text_width = bbox[2] - bbox[0] if text_width > max_width:
# 按比例缩小
scale = max_width / text_width
new_size = int(initial_size * scale)
return ImageFont.truetype(font_path, new_size)
return font

# 使用示例
text = “这是一段很长的中文文本”
font = calculate_font_size(text, max_width=200, initial_size=48)
3.2 字体样式控制
TrueType字体支持多种样式,但Pillow本身不直接提供粗体/斜体切换。需要通过以下方式实现:
方法1:使用字体文件的不同变体
# 使用不同的字体文件实现样式
styles = {
‘normal’: ‘simsun.ttc’, # 宋体(常规)
‘bold’: ‘simhei.ttc’, # 黑体(粗体)
‘italic’: ‘kaiiti.ttf’, # 楷体(斜体)
‘bold_italic’: ‘simyou.ttc’ # 幼圆(粗斜体)
}

def get_font_with_style(style_name, size=32):
“””根据样式名称获取字体”””
font_file = styles.get(style_name, ‘simsun.ttc’)
return ImageFont.truetype(font_file, size)

# 使用示例
bold_font = get_font_with_style(‘bold’, 36)
方法2:通过图像处理模拟粗体效果
def create_bold_text_effect(draw, position, text, font, fill_color=”black”):
“””
通过多次绘制模拟粗体效果
“””
x, y = position
# 绘制多个偏移版本
offsets = [(0, 1), (1, 0), (1, 1), (-1, 0), (0, -1)]
for dx, dy in offsets:
draw.text((x + dx, y + dy), text, font=font, fill=fill_color)
# 最后绘制中心文字
draw.text((x, y), text, font=font, fill=fill_color)

# 使用示例
img = Image.new(‘RGB’, (400, 200), color=’white’)
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(“simsun.ttc”, 48)
create_bold_text_effect(draw, (50, 50), “粗体效果”, font)
img.save(‘bold_text.png’)
3.3 字体颜色和透明度控制
# 基本颜色设置
draw.text((10, 10), “红色文字”, font=font, fill=(255, 0, 0))

# RGBA颜色(支持透明度)
draw.text((10, 50), “半透明文字”, font=font, fill=(255, 0, 0, 128))

# 创建带阴影的文字
def draw_text_with_shadow(draw, position, text, font, text_color=”white”, shadow_color=”black”, offset=(2, 2)):
“””绘制带阴影的文字”””
x, y = position
# 先绘制阴影
draw.text((x + offset[0], y + offset[1]), text, font=font, fill=shadow_color)
# 再绘制主文字
draw.text((x, y), text, font=font, fill=text_color)

# 使用示例
draw_text_with_shadow(draw, (50, 100), “阴影文字”, font)
4. 高级文字布局和多行文本处理
4.1 自动换行处理
def draw_multiline_text(draw, text, position, font, max_width, line_spacing=1.2, **kwargs):
“””
自动换行绘制多行文本
“””
x, y = position
line_height = font.getbbox(‘A’)[3] * line_spacing # 使用字母’A’计算行高
words = text.split(‘ ‘)
lines = []
current_line = []

for word in words:
# 检查当前行加上新词后的宽度
test_line = ‘ ‘.join(current_line + [word])
bbox = font.getbbox(test_line)
if bbox[2] – bbox[0] <= max_width: current_line.append(word) else: if current_line: lines.append(' '.join(current_line)) current_line = [word] if current_line: lines.append(' '.join(current_line)) # 绘制每一行 for i, line in enumerate(lines): draw.text((x, y + i * line_height), line, font=font, **kwargs) return len(lines) * line_height # 使用示例 long_text = "这是一个很长的中文句子,需要自动换行来适应图片的宽度限制。" img = Image.new('RGB', (400, 200), color='white') draw = ImageDraw.Draw(img) font = ImageFont.truetype("simsun.ttc", 24) draw_multiline_text(draw, long_text, (10, 10), font, max_width=380) img.save('multiline_text.png') 4.2 文字居中对齐 def draw_centered_text(draw, text, position, font, **kwargs): """ 绘制水平居中的文字 """ bbox = font.getbbox(text) text_width = bbox[2] - bbox[0] text_height = bbox[3] - bbox[1] x = position[0] - text_width // 2 y = position[1] - text_height // 2 draw.text((x, y), text, font=font, **kwargs) def draw_centered_multiline_text(draw, text, box_position, box_size, font, line_spacing=1.2, **kwargs): """ 在指定区域内绘制居中的多行文本 """ box_x, box_y = box_position box_w, box_h = box_size # 计算行数和行高 lines = text.split('\n') line_height = font.getbbox('A')[3] * line_spacing # 计算总高度 total_height = len(lines) * line_height # 计算起始Y坐标(垂直居中) start_y = box_y + (box_h - total_height) // 2 # 绘制每一行(水平居中) for i, line in enumerate(lines): bbox = font.getbbox(line) text_width = bbox[2] - bbox[0] x = box_x + (box_w - text_width) // 2 y = start_y + i * line_height draw.text((x, y), line, font=font, **kwargs) # 使用示例 img = Image.new('RGB', (400, 200), color='lightblue') draw = ImageDraw.Draw(img) font = ImageFont.truetype("simsun.ttc", 32) draw_centered_multiline_text(draw, "居中\n多行\n文本", (50, 20), (300, 160), font) img.save('centered_text.png') 5. 完整项目示例:生成带文字的图片 5.1 项目结构设计 from PIL import Image, ImageDraw, ImageFont import os from typing import Tuple, Optional class TextOnImageGenerator: """ 专业的文字图片生成器,解决乱码问题并提供丰富的文字样式 """ def __init__(self, width=800, height=600, background_color=(255, 255, 255)): self.width = width self.height = height self.background_color = background_color self.image = Image.new('RGB', (width, height), background_color) self.draw = ImageDraw.Draw(self.image) self.font_cache = {} def get_font(self, font_size=36, font_style='normal', font_path=None): """ 智能字体加载,支持缓存和样式 """ cache_key = f"{font_size}_{font_style}_{font_path}" if cache_key in self.font_cache: return self.font_cache[cache_key] # 如果没有指定字体路径,自动查找系统中文字体 if font_path is None: font_path = self._find_chinese_font() try: font = ImageFont.truetype(font_path, font_size) self.font_cache[cache_key] = font return font except Exception as e: print(f"加载字体失败: {e}") # 降级到默认字体(会乱码) return ImageFont.load_default() def _find_chinese_font(self): """ 自动查找系统中文字体 """ font_candidates = [] if os.name == 'nt': # Windows font_candidates = [ r'C:\Windows\Fonts\simsun.ttc', r'C:\Windows\Fonts\msyh.ttc', r'C:\Windows\Fonts\simhei.ttc', ] elif os.name == 'posix': # macOS/Linux font_candidates = [ '/System/Library/Fonts/PingFang.ttc', '/System/Library/Fonts/STSong.ttc', '/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc', '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc', ] for path in font_candidates: if os.path.exists(path): return path # 如果找不到,提示用户 raise FileNotFoundError( "未找到中文字体文件。请手动下载中文字体(如simsun.ttc)并指定路径。" ) def add_text(self, text, position, font_size=36, font_style='normal', fill=(0, 0, 0), align='left', max_width=None, line_spacing=1.2, shadow=False, shadow_offset=(2, 2), shadow_color=(0, 0, 0)): """ 添加文字到图片 """ font = self.get_font(font_size, font_style) # 处理自动换行 if max_width: return self._draw_wrapped_text( text, position, font, max_width, fill, line_spacing, shadow, shadow_offset, shadow_color ) else: # 简单绘制 if shadow: self._draw_text_with_shadow(position, text, font, fill, shadow_offset, shadow_color) else: self.draw.text(position, text, font=font, fill=fill) return font.getbbox(text) def _draw_wrapped_text(self, text, position, font, max_width, fill, line_spacing, shadow, shadow_offset, shadow_color): """ 绘制自动换行的文字 """ x, y = position line_height = font.getbbox('A')[3] * line_spacing # 简单的按字符换行(中文需要按字符处理) lines = [] current_line = "" for char in text: test_line = current_line + char bbox = font.getbbox(test_line) if bbox[2] - bbox[0] <= max_width: current_line = test_line else: if current_line: lines.append(current_line) current_line = char if current_line: lines.append(current_line) # 绘制每一行 for i, line in enumerate(lines): line_y = y + i * line_height if shadow: self._draw_text_with_shadow((x, line_y), line, font, fill, shadow_offset, shadow_color) else: self.draw.text((x, line_y), line, font=font, fill=fill) return (x, y, x + max_width, y + len(lines) * line_height) def _draw_text_with_shadow(self, position, text, font, fill, shadow_offset, shadow_color): """绘制带阴影的文字""" x, y = position dx, dy = shadow_offset self.draw.text((x + dx, y + dy), text, font=font, fill=shadow_color) self.draw.text((x, y), text, font=font, fill=fill) def save(self, filename): """保存图片""" self.image.save(filename) print(f"图片已保存到: {filename}") # 完整使用示例 def main(): # 创建生成器 generator = TextOnImageGenerator(width=800, height=600, background_color=(240, 240, 240)) # 添加标题(大字体,带阴影) generator.add_text( "Pillow文字绘制示例", position=(400, 50), font_size=48, fill=(30, 30, 30), shadow=True, shadow_offset=(3, 3), shadow_color=(200, 200, 200) ) # 添加副标题(中等字体) generator.add_text( "解决中文乱码问题", position=(400, 120), font_size=32, fill=(80, 80, 80) ) # 添加多行正文(自动换行) long_text = "这是一个完整的Pillow文字绘制示例,展示了如何正确加载中文字体、设置字体大小和样式,以及避免乱码问题。通过使用TrueType字体文件,我们可以完美支持中文、日文、韩文等Unicode字符。" generator.add_text( long_text, position=(50, 180), font_size=24, fill=(50, 50, 50), max_width=700, line_spacing=1.5 ) # 添加带样式的文字 generator.add_text( "粗体效果示例", position=(50, 350), font_size=36, font_style='bold', fill=(200, 0, 0) ) # 添加多语言测试 generator.add_text( "中文 English 日本語 한국어", position=(50, 420), font_size=28, fill=(0, 100, 0) ) # 保存最终图片 generator.save('pillow_text_example.png') if __name__ == '__main__': main() 6. 常见问题排查和最佳实践 6.1 乱码问题排查清单 def debug_font_issue(text): """ 调试字体问题的诊断函数 """ print("=== 字体问题诊断 ===") print(f"1. 测试文本: {text}") print(f"2. 文本编码: {text.encode('utf-8')}") print(f"3. 字符类型: {[type(c) for c in text]}") # 检查是否包含中文字符 has_chinese = any('\u4e00' <= c <= '\u9fff' for c in text) print(f"4. 包含中文: {has_chinese}") # 尝试加载字体 try: font = ImageFont.truetype("simsun.ttc", 32) print("5. 字体加载: 成功") # 测试字体渲染 bbox = font.getbbox(text) print(f"6. 文字尺寸: {bbox}") except Exception as e: print(f"5. 字体加载: 失败 - {e}") print("6. 建议: 下载中文字体文件并指定正确路径") # 使用示例 debug_font_issue("测试中文") 6.2 性能优化建议 # 1. 字体缓存:避免重复加载相同字体 font_cache = {} def get_font_cached(font_path, size): key = (font_path, size) if key not in font_cache: font_cache[key] = ImageFont.truetype(font_path, size) return font_cache[key] # 2. 批量绘制:减少ImageDraw对象创建 def batch_draw_texts(image, texts_with_styles): """ 批量绘制多个文字,提高性能 """ draw = ImageDraw.Draw(image) for item in texts_with_styles: font = get_font_cached(item['font_path'], item['size']) draw.text(item['position'], item['text'], font=font, fill=item['color']) return image # 3. 使用textbbox替代getbbox(Pillow 9.2.0+) # 新版本推荐使用textbbox,它返回更精确的边界框 def get_text_dimensions(text, font): """获取文字尺寸(推荐方式)""" try: # Pillow 9.2.0+ bbox = font.getbbox(text) # 或 font.getbbox(text) return bbox[2] - bbox[0], bbox[3] - bbox[1] except: # 旧版本兼容 return font.getsize(text) 6.3 跨平台部署注意事项 def deployable_font_loader(font_filename="simsun.ttc"): """ 部署时的字体加载策略 """ # 1. 优先使用相对路径的字体文件(推荐) local_font = os.path.join("fonts", font_filename) if os.path.exists(local_font): return local_font # 2. 其次使用环境变量指定的路径 env_font = os.environ.get("CUSTOM_FONT_PATH") if env_font and os.path.exists(env_font): return env_font # 3. 最后尝试系统字体 system_fonts = { 'nt': [r'C:\Windows\Fonts\simsun.ttc'], 'posix': ['/System/Library/Fonts/PingFang.ttc', '/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc'] } for path in system_fonts.get(os.name, []): if os.path.exists(path): return path raise FileNotFoundError("找不到字体文件,请将字体文件放在./fonts/目录或设置CUSTOM_FONT_PATH环境变量") # Docker部署示例 """ Dockerfile中添加字体: RUN apt-get update && apt-get install -y fonts-wqy-zenhei COPY fonts/simsun.ttc /usr/local/share/fonts/ """ 7. 总结 通过本文的详细讲解,您应该已经掌握了使用Pillow绘制文字时的核心要点: 必须使用TrueType字体 :这是避免乱码的唯一方法 正确加载字体 :跨平台查找系统字体或使用本地字体文件 精确控制样式 :通过字体文件和图像处理实现各种效果 高级布局 :处理自动换行、居中对齐等复杂需求 性能优化 :缓存字体、批量处理等最佳实践 记住, 字体文件是关键 。在生产环境中,建议将字体文件与代码一起部署,避免依赖系统字体。这样可以确保在任何环境下都能正确显示中文,彻底解决乱码问题。