Determining the pixel height of a line with newline characters in a pad

I am trying to draw text (which can be of any length depending on what the user enters) on a blank image. I need to split the text in new lines to avoid creating too large images, and I also need to create an image with a size related to how many characters the user enters, avoiding white space. This is what I came up with:

import PIL
import textwrap
from PIL import ImageFont, Image, ImageDraw

#Input text
usrInput = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet scelerisque nulla. Pellentesque mollis tellus ut arcu malesuada auctor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut tristique purus non ultricies vulputate"
text = textwrap.fill(usrInput,50)

#font size, color and type
fontColor = (255,255,255)
fontSize = 40
font = ImageFont.truetype("/System/Library/Fonts/AppleGothic.ttf",fontSize)

#Image size and background color
background = (200,255,0)
#imgSize = font.getsize(text)
imgSize = ImageDraw.Draw.textsize(text, font)

def CreateImg ():
    img = Image.new("RGBA", imgSize, background)
    draw = ImageDraw.Draw(img)
    draw.text((0,0), text, fontColor, font)
    img.save("test.png")


CreateImg()

. font.getsize, , , , , . , . , , ImageDraw.Draw.textsize( ImageDraw.Draw.multiline_textsize, ), :

Traceback (most recent call last):
File "pil.py", line 17, in <module>
    imgSize = ImageDraw.Draw.textsize(text, font)
AttributeError: 'function' object has no attribute 'textsize'

? ?

+4
1

, .

, , - : , .

:

from PIL import ImageFont, Image, ImageDraw
import textwrap

# Source text, and wrap it.
userinput = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet scelerisque nulla. Pellentesque mollis tellus ut arcu malesuada auctor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut tristique purus non ultricies vulputate"
text = textwrap.fill(userinput, 50)

# Font size, color and type.
fontcolor = (255, 255, 255)
fontsize = 40
font = ImageFont.truetype("/System/Library/Fonts/AppleGothic.ttf", fontsize)

# Determine text size using a scratch image.
img = Image.new("RGBA", (1,1))
draw = ImageDraw.Draw(img)
textsize = draw.textsize(text, font)

# Now that we know how big it should be, create
# the final image and put the text on it.
background = (200, 255, 0)
img = Image.new("RGBA", textsize, background)
draw = ImageDraw.Draw(img)
draw.text((0, 0), text, fontcolor, font)

img.show()
img.save("seesharp.png")
+4

Source: https://habr.com/ru/post/1611609/


All Articles