I don't know of a way of auto-sizing text with PIL, but you can do it with wand. I am not that experienced with wand
, but you can use the caption()
method if you want your text auto-wrapped and sized. I changed the code between runs to write a small amount of text and a considerably longer text in an area I marked in white:
#!/usr/bin/env python3
from wand.image import Image
from wand.drawing import Drawing
from wand.font import Font
# Create a red canvas 600x300
with Image(width=600, height=300, pseudo='xc:red') as canvas:
left, top, width, height = 10, 20, 400, 150
with Drawing() as context:
context.fill_color = 'white'
context.rectangle(left=left, top=top, width=width, height=height)
font = Font('/System/Library/Fonts/MarkerFelt.ttc')
context(canvas)
canvas.caption('Considerably longer text that will need a smaller font and some wrapping too', left=left, top=top, width=width, height=height, font=font, gravity='center')
canvas.save(filename='result.png')
There are examples of more sophisticated wrapping techniques using Python's textwrap
in the wand documentation.
Keywords: wand, image processing, python, caption, auto-wrap, auto-size, word wrap.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…