在 Pillow 中确定带有换行符的字符串的像素高度

Determining pixel height of a string with newlines in Pillow

我正在尝试在空白图像上绘制文本(可以是任意长度,具体取决于用户输入的内容)。我需要在换行符中拆分文本以避免创建太大的图像,我还需要创建一个大小与用户输入的字符数相关的图像,避免任何空 space。这是我到目前为止想出的:

import PIL
import textwrap
from PIL import ImageFont, Image, ImageDraw

#Input text
usrInput = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet scelerisque nulla. Pellentesque mollis tellus ut arcu malesuada auctor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut tristique purus non ultricies vulputate"
text = textwrap.fill(usrInput,50)

#font size, color and type
fontColor = (255,255,255)
fontSize = 40
font = ImageFont.truetype("/System/Library/Fonts/AppleGothic.ttf",fontSize)

#Image size and background color
background = (200,255,0)
#imgSize = font.getsize(text)
imgSize = ImageDraw.Draw.textsize(text, font)

def CreateImg ():
    img = Image.new("RGBA", imgSize, background)
    draw = ImageDraw.Draw(img)
    draw.text((0,0), text, fontColor, font)
    img.save("test.png")


CreateImg()

现在我遇到了一个问题。如果我使用 font.getsize 来确定图像应该有多大,它会完全按照我想要的方式工作,但前提是文本不会换行。如果是这样,它会给我单行的高度和没有换行符的全文宽度。 所以我认为这可能不是正确的方法,我决定尝试 ImageDraw.Draw.textsize(应该检测行并使用 ImageDraw.Draw.multiline_textsize 如果有多个),但它不起作用并且我得到这个错误:

Traceback (most recent call last):
File "pil.py", line 17, in <module>
    imgSize = ImageDraw.Draw.textsize(text, font)
AttributeError: 'function' object has no attribute 'textsize'

我做错了什么?我处理得很好还是有更好的解决方案?

我觉得你把语句的顺序弄错了。

在一张刚好足够大的图片上绘制文字需要两个步骤:首先,确定文字大小,然后创建该大小的图片。

这是一个工作示例:

from PIL import ImageFont, Image, ImageDraw
import textwrap

# Source text, and wrap it.
userinput = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet scelerisque nulla. Pellentesque mollis tellus ut arcu malesuada auctor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut tristique purus non ultricies vulputate"
text = textwrap.fill(userinput, 50)

# Font size, color and type.
fontcolor = (255, 255, 255)
fontsize = 40
font = ImageFont.truetype("/System/Library/Fonts/AppleGothic.ttf", fontsize)

# Determine text size using a scratch image.
img = Image.new("RGBA", (1,1))
draw = ImageDraw.Draw(img)
textsize = draw.textsize(text, font)

# Now that we know how big it should be, create
# the final image and put the text on it.
background = (200, 255, 0)
img = Image.new("RGBA", textsize, background)
draw = ImageDraw.Draw(img)
draw.text((0, 0), text, fontcolor, font)

img.show()
img.save("seesharp.png")