Oliver H Gray
Oliver H Gray

Reputation: 105

Create PIL ImageFont image that is the exact size of the text

Is it possible to render text with PIL, but make the image as small dimension-wise as possible? Currently I am having to make a large image, since I can't know how long the string being entered will be, however the text renders in the top left corner, leaving loads of extra space in the image.

Would it be possible to shrink the image to the size of the text that is rendered? Or predict the size of the text before it is rendered so the correct size image can be created?

Here is the code I am currently using:

font = ImageFont.truetype("BebasNeue.ttf", 45)

image = Image.new("RGBA", (400, 400), None)
draw = ImageDraw.Draw(image)
draw.text((0, 0), self.text, font=font, fill="white")
del draw

Upvotes: 0

Views: 990

Answers (1)

Armin Rigo
Armin Rigo

Reputation: 13000

The font objects have a method getsize(text) that returns a tuple (width, height).

Upvotes: 1

Related Questions