Search code examples
pythonpython-imaging-library

how the Image.ImageFont.ImageFont.getsize() command works?


I need to use this command to select the text with the biggest font size but after countless tries nothing works

I've tried: Image.ImageFont.ImageFont.getsize(text) {text is a variable for the text it scans through}

[ERROR]: TypeError: getsize() missing 1 required positional argument: 'text'

Image.ImageFont.ImageFont.getsize(text = 'Lorem Ipsum')

[ERROR]: TypeError: getsize() missing 1 required positional argument: 'self'

Image.ImageFont.ImageFont.getsize(self, text = 'Lorem Ipsum')

[ERROR]: NameError: name 'self' is not defined

I don't quite understand what self is supposed to do/mean.

Side Note: If the code is supposed to look through text and find the biggest font size, why do I have to choose a word whose font size it should determine, shouldn't it do that for the whole passage?

Here is my code in its entirety:

from PIL import Image, ImageFont

image = Image.open('screenshot - copy.bmp') 

fontget = ImageFont.ImageFont.getsize(text = 'food')
print(fontget)

What I want it to do is scan through a passage and return different font sizes. From there I will make it print the text with the biggest font size.


Solution

  • [ERROR]: TypeError: getsize() missing 1 required positional argument: 'text'
    

    The previous error means that you called an instance method on a class, not an instance of a class. You have to instantiate the ImageFont class by loading a font first.

    >>> from PIL import ImageFont
    >>> font = ImageFont.load_default()
    >>> font.getsize('hello world')
    (66, 11)
    

    Side Note: If the code is supposed to look through text and find the biggest font size, why do I have to choose a word whose font size it should determine, shouldn't it do that for the whole passage?

    This is not what getsize() does. It returns the size of text that PIL.ImageDraw.Draw.text() would draw in the selected font.

    >>> font.getsize('h')
    (6, 11)
    >>> font.getsize('hello')
    (30, 11)
    >>> font.getsize('hello hello this is long text and you can see x gets bigger because the text gets wider')
    (522, 11)