在 Pillow 10+ 中将 ImageFont.getsize(text) 替换为 ImageFont.textbbox(text) 的简单方法

问题描述 投票:0回答:1

在 Pillow 10 之前,您可以使用 getsize() 方法,但在 10+ 之后,该方法已被弃用。 您可以轻松地将其更改为 getbbox() 添加两行。

import streamlit as st
from PIL import Image, ImageFont, ImageDraw
import requests
from io import BytesIO


def text_on_image(image, text, font_size, color):
    req = requests.get('https://github.com/googlefonts/roboto/raw/main/src/hinted/Roboto-Regular.ttf')
    img = Image.open(image)
    font = ImageFont.truetype(BytesIO(req.content), font_size)
    draw = ImageDraw.Draw(img)

    image_width, image_height = img.size
    # old way using getsize()
    # text_width, text_height = font.getsize(text)
    # using pillow 10+
    left, top, right, bottom = font.getbbox(text)
    text_width = right - left
    text_height = bottom - top

    draw.text(
        ((image_width - text_width) / 2, (image_height - text_height) / 2),
        text,
        fill=color,
        font=font
    )

    img.save('last_image.jpg')

我希望您能对这段代码有所帮助。

python python-imaging-library
1个回答
0
投票

使用时

def getsize(font, text):
    left, top, right, bottom = font.getbbox(text)
    return right - left, bottom - top

您可以将

font.getsize(text)
替换为
getsize(font, text)

© www.soinside.com 2019 - 2024. All rights reserved.