Преобразование текста в изображение для всех типов шрифтов, доступных в fontconfig - PullRequest
0 голосов
/ 31 августа 2018

Я нашел код из stackoverflow для преобразования текста в изображение, но он не преобразовывает txt в img для всех типов шрифтов, доступных в списке шрифтов? Почему так?

Ссылка: Как я могу загрузить файл шрифта с PIL.ImageFont.truetype без указания абсолютного пути?

Код:

from PIL import Image,ImageDraw,ImageFont
import fontconfig

# find a font file
fonts = fontconfig.query(lang='en')
for i in range(1, len(fonts)):
    if fonts[i].fontformat == 'TrueType':
        absolute_path = fonts[i].file
        break

# the rest is like the original code:
# sample text and font
unicode_text = u"Hello World!"
font = ImageFont.truetype(absolute_path, 28, encoding="unic")

# get the line size
text_width, text_height = font.getsize(unicode_text)

# create a blank canvas with extra space between lines
canvas = Image.new('RGB', (text_width + 10, text_height + 10), "orange")

# draw the text onto the text canvas, and use black as the text color
draw = ImageDraw.Draw(canvas)
draw.text((5,5), u'Hello World!', 'blue', font)

# save the blank canvas to a file
canvas.save("unicode-text.png", "PNG")
canvas.show()

Я изменил этот код для преобразования всех шрифтов в изображения, и мой код приведен ниже:

from PIL import Image,ImageDraw,ImageFont
import fontconfig

# sample text and font
unicode_text = u"Hello World!"

count = 0
for fonts in fontconfig.query(lang="en"):
    font = ImageFont.truetype(fonts, 28, encoding="unic")

    # get the line size
    text_width, text_height = font.getsize(unicode_text)

    # create a blank canvas with extra space between lines
    canvas = Image.new('RGB', (text_width + 10, text_height + 10), "orange")

    # draw the text onto the text canvas, and use black as the text color
    draw = ImageDraw.Draw(canvas)
    draw.text((5, 5), u'Hello World!', 'blue', font)

    # save the blank canvas to a file
    canvas.save("Helloworld" + str(count) + ".png", "PNG")
    count = count+1
    canvas.show()

Код ошибки:

Traceback (most recent call last):
  File "/home/noob/PycharmProjects/SignageAug/scribble.py", line 34, in <module>
    font = ImageFont.truetype(fonts, 28, encoding="unic")
  File "/home/noob/anaconda3/lib/python3.5/site-packages/PIL/ImageFont.py", line 228, in truetype
    return FreeTypeFont(font, size, index, encoding)
  File "/home/noob/anaconda3/lib/python3.5/site-packages/PIL/ImageFont.py", line 131, in __init__
    self.font = core.getfont(font, size, index, encoding)
OSError: invalid pixel size

Process finished with exit code 1

Итак, может ли кто-нибудь помочь мне получить txt для изображения почти всех типов шрифтов из этого кода?

...