Skip to content
Discussion options

You must be logged in to vote

To adjust the size of the image to fit the text, you can

from PIL import Image, ImageFont, ImageDraw
font = ImageFont.load_default(size=16)
text = "Sample Text"
w, h = font.getbbox(text)[2:]
img = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(img)
draw.text((0, 0), text, (255,255,255), font=font)
img.save('sample-out.jpg')

However, you've also said you'd like the text to be aligned to the center. That doesn't mean anything if the image exactly fits the width of a single line of text, so I presume you're dealing with multiple lines of text?

from PIL import Image, ImageFont, ImageDraw
font = ImageFont.load_default(size=16)
text = "Sample\nText"
img = Image.new("RGB", (0, 0))
draw = ImageDraw

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@SohamTilekar
Comment options

@radarhere
Comment options

Answer selected by SohamTilekar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants