[Python] Converting Text into an Image

Discussão em 'Python' iniciado por Stack, Junho 14, 2025.

  1. Stack

    Stack Membro Participativo

    I have been developing a program that reads a text from a text file. After reading the text, I want to convert the text to an image but with random attributes such as font style, size and more. The thing is the output image should not exceed 700(image_width) and 100(image_height). When the chosen random font is large, the text dimension exceeds the limit (horizontally and vertically).

    What I want is to adjust the paragraph width so that it can fit horizontally and when it exceeds vertically, just include those text that can be fitted in the height limit.

    What my current code does is when the text size exceeds, it chooses another random smaller font so that it will not exceed the dimension limit. This is not what I want since it will only reproduce text with small fonts.

    from PIL import Image
    from PIL import ImageDraw
    from PIL import ImageFont

    from random import seed
    from random import randint
    import numpy as np
    import os.path

    #Constant dimensions of the image.
    image_width = 700
    image_height = 1000

    #Returns the text size in terms of width and height.
    def getSize(txt, font):
    testImg = Image.new('RGB', (1, 1))
    testDraw = ImageDraw.Draw(testImg)
    return testDraw.textsize(txt, font)

    #Randomize XY coordinate of the text in white background image.
    def get_xy_coordinates(text, font):
    width, height = getSize(text, font)
    xy = (randint(1, image_width - width), randint(1, image_height - height ))
    return xy

    if __name__ == '__main__':
    seed()
    file_counter = 1


    fonts = ['arial.ttf', 'arialbd.ttf', 'arialbi.ttf', 'ariali.ttf', 'ARIALN.TTF', 'ARIALNB.TTF', 'ARIALNBI.TTF', 'ARIALNI.TTF','ariblk.ttf','ARLRDBD.TTF','georgia.ttf','georgiab.ttf','georgiai.ttf','georgiaz.ttf','GRGAREF.TTF','OCRAEXT.TTF','OCRAStd.otf', 'times.ttf','timesbd.ttf','timesbi.ttf','timesi.ttf','verdana.ttf','verdanab.ttf','verdanai.ttf','verdanaz.ttf', 'VERDREF.TTF']

    while True:


    print(file_counter)

    if not os.path.isfile('text/' + str (file_counter) + '.txt'):
    break

    text = open('text/' + str (file_counter) + ".txt", encoding="utf8")

    text = text.read()
    font_number = randint(0,25)

    fontname = 'fonts/' + fonts[font_number]

    #Limits text dimension to constant maximum dimensions of training and testing images.
    while True:
    fontsize = randint(10, 50)
    font = ImageFont.truetype(fontname, fontsize)
    width, height = getSize(text, font)
    if (width < image_width) and (height < image_height):
    break

    #Creates an image with white background of constant size.
    img = Image.new('RGB', (image_width, image_height), 'white')
    d = ImageDraw.Draw( img)
    #d.text(get_xy_coordinates(text, font), text, fill='black', font=font)
    img.save("text_images/" + str(file_counter) + ".png")
    file_counter = file_counter + 1


    Notes:

    Link for the text files used.

    Link for the font files used.

    Note : Text files content varies. Some contains few words, some are many. I dont want to distort the text's width and height aspect ratio.

    Continue reading...

Compartilhe esta Página