1

i am having some problems and can't seem to find an answer. I Want to write a string into a .png with the PIL lib, but scince my string is too long to fit the image, and i can't change the size of the image, i want that the string automatticly fits itself to the image.

fontsize = 20
img = Image.open('pythontest.png')
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("fonts/NotoSans-Black.ttf", fontsize)

#Here is my problem 
draw.text((140, 140), "A String that is way to long for this picture, i want to format 
this sting so that it can automatticly fit this image",font=font,fill=(255, 255, 255))


img.save("Done.png")

I hope, that i could elaborate my problem clearly, if not i can answer questions.

Thanks for your help! (my image has the format x = 720, y = 357)

  • @AhmedAEK's answer may help, but my read on this is that you don't want to wrap the text but rather want to shrink it. I'm not all that familiar with the PIL lib, but I would think that what you'd want to do is render the string to its own image so that you can figure out how bit it is. Then you have a couple of options: 1) change the font size proportionally and the re-draw the text onto the target image, or 2) shrink the image of your text down so that it fits on your image, and then composite the text image onto the target image. ... – CryptoFool Sep 18 '22 at 10:46
  • ...this is all somewhat vague ramblings on my part, as I haven't used PIL in many years. Just trying to give you some starting thoughts. – CryptoFool Sep 18 '22 at 10:48
  • Check out this SO questio. I think this might help you: https://stackoverflow.com/questions/43828955/measuring-width-of-text-python-pil – CryptoFool Sep 18 '22 at 11:01
  • Textwrap is the libary i was searching for, thanks for your help – A_GUY_WITH_PC Sep 18 '22 at 14:16

0 Answers0