How to resize the font based on the length of the text? #6891
-
| Hi Please note that I have thousands of quotes so I need to bulk print those quotes. | 
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
| Hi. Pillow doesn't have an autoresize function, but it does have functions to determine how large text will be once it is drawn - you might be interested in  Here's a demonstration. from PIL import Image, ImageDraw, ImageFont
import urllib.request
req = urllib.request.urlopen("https://python-pillow.org/dist/5d1875f38a1f87b7dbc3.png")
width = 750
height = 500
im = Image.open(req).resize((width, height))
draw = ImageDraw.Draw(im, "RGBA")
quote = "Pillow is the friendly PIL fork by Alex Clark and Contributors. PIL is the Python Imaging Library by Fredrik Lundh and Contributors. As of 2019, Pillow development is supported by Tidelift. The Python Imaging Library adds image processing capabilities to your Python interpreter. This library provides extensive file format support, an efficient internal representation, and fairly powerful image processing capabilities. The core image library is designed for fast access to data stored in a few basic pixel formats. It should provide a solid foundation for a general image processing tool."
text_width = width * 0.8
text_max_height = height * 0.8
size = 36
while size > 9:
	# Insert your own font path here
	font_path = "Times New Roman.ttf"
	font = ImageFont.truetype(font_path, size, layout_engine=ImageFont.Layout.BASIC)
	lines = []
	line = ""
	for word in quote.split():
		proposed_line = line
		if line:
			proposed_line += " "
		proposed_line += word
		if font.getlength(proposed_line) <= text_width:
			line = proposed_line
		else:
			# If this word was added, the line would be too long
			# Start a new line instead
			lines.append(line)
			line = word
	if line:
		lines.append(line)
	quote = "\n".join(lines)
	x1, y1, x2, y2 = draw.multiline_textbbox((0, 0), quote, font, stroke_width=2)
	w, h = x2 - x1, y2 - y1
	if h <= text_max_height:
		break
	else:
		# The text did not fit comfortably into the image
		# Try again at a smaller font size
		size -= 1
draw.multiline_text((width / 2 - w / 2 - x1, height / 2 - h / 2 - y1), quote, font=font, align="center", stroke_width=2, stroke_fill="#000")
im.save("out.png") | 
Beta Was this translation helpful? Give feedback.

Hi. Pillow doesn't have an autoresize function, but it does have functions to determine how large text will be once it is drawn - you might be interested in
getlength(),getbbox()ormultiline_textbbox().Here's a demonstration.