Python PIL如何为图片自适应居中的动态文本添加灰色背景框
Python PIL 文本自适应灰色背景框实现
核心方案不需要单独创建文本图层叠加,直接在绘制文本前先精准获取文本的实际渲染边界,按需求加内边距后绘制灰色背景,再绘制上层文本即可,完全适配任意长度的换行文本。
修正后完整代码
from PIL import Image, ImageDraw, ImageFont import textwrap from string import ascii_letters # 可自定义配置项 PADDING = 25 # 文本与灰色背景框的内边距 BG_COLOR = (120, 120, 120, 180) # 背景色:灰色+透明度,最后一位数值越小透明度越高 TEXT_COLOR = "#000000" FONT_SIZE = 50 TEXT_MAX_WIDTH_RATIO = 0.83 # 文本区域最大宽度占原图宽度的比例 CORNER_RADIUS = 10 # 背景框圆角大小,不需要圆角可设为0 img = Image.open(fp="background.jpg", mode="r").convert("RGBA") font = ImageFont.truetype(font="arial", size=FONT_SIZE) draw = ImageDraw.Draw(im=img) origin_text = """Simplicity--the art of maximizing the amount of work not done--is essential.""" # 计算单字符平均宽度,自动适配换行 avg_char_width = sum(font.getlength(char) for char in ascii_letters) / len(ascii_letters) max_char_per_line = int(img.size[0] * TEXT_MAX_WIDTH_RATIO / avg_char_width) wrapped_text = textwrap.fill(text=origin_text, width=max_char_per_line) # 文本居中坐标 center_pos = (img.size[0] / 2, img.size[1] / 2) # 精准获取多行文本渲染后的实际边界 text_bound = draw.textbbox( xy=center_pos, text=wrapped_text, font=font, anchor="mm" ) # 加上内边距得到背景框的绘制坐标 bg_bound = ( text_bound[0] - PADDING, text_bound[1] - PADDING, text_bound[2] + PADDING, text_bound[3] + PADDING ) # 先绘制灰色背景框,再绘制上层文本 draw.rounded_rectangle(xy=bg_bound, radius=CORNER_RADIUS, fill=BG_COLOR) draw.text(xy=center_pos, text=wrapped_text, font=font, fill=TEXT_COLOR, anchor="mm") # 若保存为jpg格式,需转回RGB模式丢弃alpha通道 img = img.convert("RGB") img.show()
实现关键点
- 放弃估算文本尺寸的思路,直接调用
draw.textbbox()获取Pillow实际渲染文本后的真实边界坐标,从根源解决背景框和文本尺寸不匹配的问题 - 支持任意长度文本:文本自动换行后会重新计算整体边界,背景框会随文本尺寸自动伸缩,始终保持居中
- 所有视觉参数都可自由调整:包括内边距、背景色透明度、圆角大小、文本占比等
目标效果参考

内容的提问来源于stack exchange,提问作者holograms
相关产品推荐
相关产品推荐

