see*_*arp 8 python python-imaging-library python-2.7 pillow
我正在尝试在空白图像上绘制文本(根据用户输入的内容可以是任意长度)。我需要在换行符中拆分文本以避免创建太大的图像,我还需要创建一个图像,其大小与用户输入的字符数有关,避免出现任何空白空间。这是我到目前为止想出的:
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()
Run Code Online (Sandbox Code Playgroud)
现在我有一个问题。如果我使用 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'
Run Code Online (Sandbox Code Playgroud)
我在做什么错?我很好地处理了这个问题还是有更好的解决方案?
我认为你的陈述顺序有点混乱。
在应该刚好足够大的图像上绘制文本是一个两步过程:首先,确定文本大小,然后创建该大小的图像。
这是一个工作示例:
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")
Run Code Online (Sandbox Code Playgroud)