gpt4 book ai didi

python - 在 Python 中将 .txt 文件转换为图像

转载 作者:太空狗 更新时间:2023-10-30 00:49:26 25 4
gpt4 key购买 nike

我有一些代码可以将图像转换为 ascii 艺术图像。目前它将其输出为 .txt 文件,但该文件可以包含数十万个字符。如何将文件转换为图像,例如 .png 文件?

目前它是根据像素密度构建一个字符向量,然后将向量写入.txt图像。

最佳答案

如果我理解正确的话,您想要的图像看起来就像有人截取了 ascii 艺术的屏幕截图,就像它在一个巨大的无限文本编辑器中看起来一样。

我做了类似的事情,用 PILLOW 以编程方式生成文本。这是一个修改自 this 的示例我的代码。希望这段代码能帮助您和其他人避免我为弄清楚如何使事情看起来合理而不得不做的摆弄。

这是一个由下面的代码生成的示例结果。

enter image description here

该代码是对链接库的直接修改,以使用文本文件而不是字符串。您应该能够将其粘贴到控制台或文件中并直接运行。

from math import ceil

from PIL import (
Image,
ImageFont,
ImageDraw,
)

PIL_GRAYSCALE = 'L'
PIL_WIDTH_INDEX = 0
PIL_HEIGHT_INDEX = 1
COMMON_MONO_FONT_FILENAMES = [
'DejaVuSansMono.ttf', # Linux
'Consolas Mono.ttf', # MacOS, I think
'Consola.ttf', # Windows, I think
]


def main():
image = textfile_to_image('content.txt')
image.show()
image.save('content.png')


def textfile_to_image(textfile_path):
"""Convert text file to a grayscale image.

arguments:
textfile_path - the content of this file will be converted to an image
font_path - path to a font file (for example impact.ttf)
"""
# parse the file into lines stripped of whitespace on the right side
with open(textfile_path) as f:
lines = tuple(line.rstrip() for line in f.readlines())

# choose a font (you can see more detail in the linked library on github)
font = None
large_font = 20 # get better resolution with larger size
for font_filename in COMMON_MONO_FONT_FILENAMES:
try:
font = ImageFont.truetype(font_filename, size=large_font)
print(f'Using font "{font_filename}".')
break
except IOError:
print(f'Could not load font "{font_filename}".')
if font is None:
font = ImageFont.load_default()
print('Using default font.')

# make a sufficiently sized background image based on the combination of font and lines
font_points_to_pixels = lambda pt: round(pt * 96.0 / 72)
margin_pixels = 20

# height of the background image
tallest_line = max(lines, key=lambda line: font.getsize(line)[PIL_HEIGHT_INDEX])
max_line_height = font_points_to_pixels(font.getsize(tallest_line)[PIL_HEIGHT_INDEX])
realistic_line_height = max_line_height * 0.8 # apparently it measures a lot of space above visible content
image_height = int(ceil(realistic_line_height * len(lines) + 2 * margin_pixels))

# width of the background image
widest_line = max(lines, key=lambda s: font.getsize(s)[PIL_WIDTH_INDEX])
max_line_width = font_points_to_pixels(font.getsize(widest_line)[PIL_WIDTH_INDEX])
image_width = int(ceil(max_line_width + (2 * margin_pixels)))

# draw the background
background_color = 255 # white
image = Image.new(PIL_GRAYSCALE, (image_width, image_height), color=background_color)
draw = ImageDraw.Draw(image)

# draw each line of text
font_color = 0 # black
horizontal_position = margin_pixels
for i, line in enumerate(lines):
vertical_position = int(round(margin_pixels + (i * realistic_line_height)))
draw.text((horizontal_position, vertical_position), line, fill=font_color, font=font)

return image


if __name__ == '__main__':
main()

顺便说一下,所有的代码不应该塞进一个函数中,但我认为这样更容易理解示例代码。

关于python - 在 Python 中将 .txt 文件转换为图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29760402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com