如何使用Pillow在图片上添加可自动适配区域的文本(不使用Wand)
Pillow图片文本边界适配实现
基于Pillow原生文本测量能力实现两个核心需求:按可用宽度自动换行、自动匹配适配区域的最大字号,无需第三方依赖。
核心使用API
font.getbbox("Hg")测量当前字体的实际行高,避免不同字体行高不一致导致的排版错位ImageDraw.textlength()测量单行文本的实际渲染宽度,用于判断换行节点
完整可运行代码
from PIL import Image, ImageDraw, ImageFont def get_adapted_font(draw, text_content, max_font_size, min_font_size, available_width, available_height, font_path, line_spacing=10): # 从最大字号开始向下匹配,找到能放下全部文本的最大字号 current_size = max_font_size while current_size >= min_font_size: font = ImageFont.truetype(font_path, current_size) line_height = font.getbbox("Hg")[3] + line_spacing # 按可用宽度拆分换行 lines = [] current_line = [] # 按空格拆分单词,避免英文单词截断 words = text_content.split(" ") for word in words: test_line = " ".join(current_line + [word]) line_width = draw.textlength(test_line, font=font) if line_width <= available_width: current_line.append(word) else: lines.append(" ".join(current_line)) current_line = [word] lines.append(" ".join(current_line)) total_height = len(lines) * line_height if total_height <= available_height: return font, lines, line_height current_size -= 2 # 到最小字号仍超出区域时,采用最小字号绘制,超出部分自动裁切 font = ImageFont.truetype(font_path, min_font_size) line_height = font.getbbox("Hg")[3] + line_spacing lines = [] current_line = [] words = text_content.split(" ") for word in words: test_line = " ".join(current_line + [word]) line_width = draw.textlength(test_line, font=font) if line_width <= available_width: current_line.append(word) else: lines.append(" ".join(current_line)) current_line = [word] lines.append(" ".join(current_line)) return font, lines, line_height def pic_mart(template=None, new_image_name="cropped_picture.jpg", text_content="Only one thing is ever guaranteed, that is that you will definitely not achieve the goal if you don't take the shot.", text_area_margin=(100, 100, 100, 100), max_font_size=50, min_font_size=20, font_path=r'C:\Users\System-Pc\Desktop\arial.ttf', text_color=(125, 200, 200)): try: # 打开模板图或新建纯色画布 if template: img = Image.open(template) else: img = Image.new('RGB', (1280,720), (100, 100, 200)) width, height = img.size print(f"图片尺寸 高:{height} 宽:{width}") d1 = ImageDraw.Draw(img) # 计算文本可用区域宽高 margin_left, margin_top, margin_right, margin_bottom = text_area_margin available_width = width - margin_left - margin_right available_height = height - margin_top - margin_bottom # 获取适配的字体与排版结果 adapted_font, lines, line_height = get_adapted_font( draw=d1, text_content=text_content, max_font_size=max_font_size, min_font_size=min_font_size, available_width=available_width, available_height=available_height, font_path=font_path ) # 逐行绘制文本 for idx, line in enumerate(lines): y_pos = margin_top + idx * line_height d1.text((margin_left, y_pos), line, font=adapted_font, fill=text_color) img.show() img.save(new_image_name) except Exception as e: print("Oops! occurred", e.__class__) pic_mart()
可自定义调整参数
- text_area_margin:四元组格式,依次为文本区域距离图片左、上、右、下的边距,按需修改即可适配不同的可用边界
- max_font_size / min_font_size:设置字号的调整范围,程序会自动在范围内匹配能放下全部文本的最大字号
- line_spacing:行间距,默认10像素,可根据需要调整避免文本过挤
- 如需支持中文逐字换行,可将
get_adapted_font内的按空格拆分单词的逻辑,改为按字符拆分逻辑(即words = list(text_content)),即可实现中文不截断换行
内容的提问来源于stack exchange,提问作者Rudresh Mehta
相关产品推荐
相关产品推荐

