How to make text image #7646
-
I want to make the Text image Using this Library. My old Code: draw = ImageDraw.Draw(img)
# font = ImageFont.truetype(<font-file>, <font-size>)
font = ImageFont.truetype(size=16)
# draw.text((x, y),"Sample Text",(r,g,b))
draw.text((0, 0),"Sample Text",(255,255,255),font=font)
img.save('sample-out.jpg') |
Beta Was this translation helpful? Give feedback.
Answered by
radarhere
Dec 28, 2023
Replies: 1 comment 2 replies
-
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.Draw(img)
w, h = draw.multiline_textbbox((0, 0), text, font)[2:]
img = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(img)
draw.text((0, 0), text, (255,255,255), font=font, align="center")
img.save('sample-out.jpg') |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
SohamTilekar
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To adjust the size of the image to fit the text, you can
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?