在Python中将.txt文件转换为图像
我有一些将图像转换为ascii艺术图像的代码。 目前它以.txt文件的形式输出,但该文件可以有几十万个字符。如何将文件转换为.png文件等图像 目前,它基于像素密度构建字符向量,然后将向量写入.txt图像。请查看(文档) 从以上链接的文档中: 下面是一个简单的例子:在Python中将.txt文件转换为图像,python,ipython,Python,Ipython,我有一些将图像转换为ascii艺术图像的代码。 目前它以.txt文件的形式输出,但该文件可以有几十万个字符。如何将文件转换为.png文件等图像 目前,它基于像素密度构建字符向量,然后将向量写入.txt图像。请查看(文档) 从以上链接的文档中: 下面是一个简单的例子: import ImageFont, ImageDraw draw = ImageDraw.Draw(image) # use a bitmap font font = ImageFont.load("arial.pil") d
import ImageFont, ImageDraw
draw = ImageDraw.Draw(image)
# use a bitmap font
font = ImageFont.load("arial.pil")
draw.text((10, 10), "hello", font=font)
# use a truetype font
font = ImageFont.truetype("arial.ttf", 15)
draw.text((10, 25), "world", font=font)
若我理解正确的话,你们想要的图像看起来就像有人截取了ascii艺术的屏幕截图一样,就像在一个巨大的无限文本编辑器中一样 我做了一些类似的事情,用枕头编程生成文本。下面是一个根据我的代码修改的示例。希望这段代码能帮助您和其他人避免我为了弄清楚如何使事情看起来合理而不得不做的那些琐事 下面是由下面的代码生成的示例结果 该代码是对链接库的直接修改,用于处理文本文件而不是字符串
import PIL
import PIL.Image
import PIL.ImageFont
import PIL.ImageOps
import PIL.ImageDraw
PIXEL_ON = 0 # PIL color to use for "on"
PIXEL_OFF = 255 # PIL color to use for "off"
def main():
image = text_image('content.txt')
image.show()
image.save('content.png')
def text_image(text_path, font_path=None):
"""Convert text file to a grayscale image with black characters on a white background.
arguments:
text_path - the content of this file will be converted to an image
font_path - path to a font file (for example impact.ttf)
"""
grayscale = 'L'
# parse the file into lines
with open(text_path) as text_file: # can throw FileNotFoundError
lines = tuple(l.rstrip() for l in text_file.readlines())
# choose a font (you can see more detail in my library on github)
large_font = 20 # get better resolution with larger size
font_path = font_path or 'cour.ttf' # Courier New. works in windows. linux may need more explicit path
try:
font = PIL.ImageFont.truetype(font_path, size=large_font)
except IOError:
font = PIL.ImageFont.load_default()
print('Could not use chosen font. Using default.')
# make the background image based on the combination of font and lines
pt2px = lambda pt: int(round(pt * 96.0 / 72)) # convert points to pixels
max_width_line = max(lines, key=lambda s: font.getsize(s)[0])
# max height is adjusted down because it's too large visually for spacing
test_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
max_height = pt2px(font.getsize(test_string)[1])
max_width = pt2px(font.getsize(max_width_line)[0])
height = max_height * len(lines) # perfect or a little oversized
width = int(round(max_width + 40)) # a little oversized
image = PIL.Image.new(grayscale, (width, height), color=PIXEL_OFF)
draw = PIL.ImageDraw.Draw(image)
# draw each line of text
vertical_position = 5
horizontal_position = 5
line_spacing = int(round(max_height * 0.8)) # reduced spacing seems better
for line in lines:
draw.text((horizontal_position, vertical_position),
line, fill=PIXEL_ON, font=font)
vertical_position += line_spacing
# crop the text
c_box = PIL.ImageOps.invert(image).getbbox()
image = image.crop(c_box)
return image
if __name__ == '__main__':
main()
顺便说一句,所有这些代码可能不应该塞进一个函数中,但我认为它使示例代码更简单。我喜欢上面的ImageFont ImageDraw解决方案,因为它要短得多。但它并没有像我尝试的那样起作用。因此,我找到了产生期望输出的方法 在下面的示例代码1中,生成白色图像。之后,将测试写入图像:
from PIL import Image, ImageFont, ImageDraw
img = Image.new('RGB', (200, 50), color = (255,255,255))
fnt = ImageFont.truetype("Pillow/Tests/fonts/FreeMono.ttf", 30)
ImageDraw.Draw(img).text((0,0), "hello world", font=fnt, fill=(0,0,0))
img
为了澄清,该.txt文件是ascii艺术文件,您需要文本的图像(如屏幕截图)?是的,完全正确。我想输出一个类似于.txt文件的png文件。我发布了一个基于我过去制作的东西的答案。在未来,我建议您投入更多的精力来创建一个。我认为你的问题和更多的答案会受到热烈的欢迎,因为这表明你在这个问题上付出了一些努力。在这种情况下,如果你对代码一无所知,至少你应该提供一个示例输入,并尽可能描述你想要的输出。我已经有一段时间没有使用PIL了,所以我不知道它的状态,也不知道枕头已经成功了-我已经更新了答案来反映这一点。问题是“如何将文件转换为.png文件之类的图像?”我认为,指向提供方法的库是一个合适的答案。如果您可以使用Pillow(或任何其他库)显示一段工作代码,该库使用ASCII艺术读取并输出png,我肯定会支持您的答案。