使用 ‘textsize’ 的目标通常是拿到图像中文字的尺寸,结果发现 CSDN 和 知乎上有很多类似的代码,均使用了 ImageDraw.textsize()
而通过查阅 PIL 库的官方文档,发现 textsize() 函数被 remove 掉了,现在用的话可以使用ImageDraw.textbbox(), ImageDraw.textlength() and ImageDraw.multiline_textbbox()
(文档指路https://pillow.readthedocs.io/en/stable/releasenotes/10.0.0.html#font-size-and-offset-methods)
以 ImageDraw.textbbox() 为例
该函数总结如下,更详细的信息可参考文档https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html#PIL.ImageDraw.ImageDraw.textbbox
ImageDraw.textbbox(xy, text, font=None, anchor=None, spacing=4, align='left', direction=None, features=None, language=None, stroke_width=0, embedded_color=False, font_size=None)[source]
返回给定文本相对于给定锚点在指定字体、方向、特性和语言下渲染时的边界框(以像素为单位)。仅支持TrueType字体。
使用 textlength()以1/64像素精度获取后续文本的偏移量。边界框包括一些字体的额外边距,例如斜体或粗体。
常用参数:
- xy – 文本的锚点坐标。
- text – 要测量的文本。如果包含换行符,则文本将传递给multiline_textbbox()。
- font – FreeTypeFont实例。
- font_size –如果未提供font,则为默认字体使用的大小。仅限关键字参数。
返回:
(left, top, right, bottom) 边界框
以下代码为 .textbox() 的示例
from PIL import Image, ImageFont, ImageDraw
def create_text_image(text, font_path, font_size, text_color, background_color=(255, 255, 255), margin=(10, 5), save_path=None):
# Load the font
font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
# Create a temporary image and drawing context
temp_image = Image.new("RGB", (1, 1), background_color)
temp_draw = ImageDraw.Draw(temp_image)
# Calculate the bounding box of the text
bbox = temp_draw.textbbox((0, 0), text, font=font)
# Calculate the size of the image
image_width = bbox[2] - bbox[0] + 2 * margin[0]
image_height = bbox[3] - bbox[1] + 2 * margin[1]
# Create the final image
image = Image.new("RGB", (image_width, image_height), background_color)
draw = ImageDraw.Draw(image)
# Draw text on the image
draw.text((margin[0] - bbox[0], margin[1] - bbox[1]), text, font=font, fill=text_color)
# Save the image if save_path is provided
if save_path:
image.save(save_path)
return image
if __name__ == "__main__":
# text = "Louis Vuitton"
# text = "ルイ・ヴィトン"
# text = '루이비통'
# text = 'Луи Виттон'
# text = 'หลุยส์ วิตตอง'
text = '路易威登'
font_path = '/path/to/font_styles/thai-Chonburi-Regular.ttf'
font_size = 400
save_path = '/path/to/lv-chi-3.png'
text_color= "#000000"
create_text_image(text, font_path, font_size, text_color, save_path=save_path)