我有一个文本文件,我想保存为图像,这可以在python中做吗?
文本文件只是一个常规的字符串列表,如文章,我想保存为PNG。我搜索谷歌和堆栈溢出但无济于事。
答案 0 :(得分:0)
让这个工作得很好,以便最终文本的格式很好,并非易事。然而,这里有一些我最近写的代码可能会让你开始:
import PIL, math
from PIL import ImageFont, ImageDraw, Image
text='''It was a bright cold day in April, and the clocks were striking thirteen. Winston Smith, his chin nuzzled into his breast in an effort to escape the vile wind, slipped quickly through the glass doors of Victory Mansions, though not quickly enough to prevent a swirl of gritty dust from entering along with him. The hallway smelt of boiled cabbage and old rag mats. At one end of it a coloured poster, too large for indoor display, had been tacked to the wall. It depicted simply an enormous face, more than a metre wide: the face of a man of about forty-five, with a heavy black moustache and ruggedly handsome features. Winston made for the stairs. It was no use trying the lift. Even at the best of times it was seldom working, and at present the electric current was cut off during daylight hours. It was part of the economy drive in preparation for Hate Week. The flat was seven flights up, and Winston, who was thirty-nine and had a varicose ulcer above his right ankle, went slowly, resting several times on the way. On each landing, opposite the lift-shaft, the poster with the enormous face gazed from the wall. It was one of those pictures which are so contrived that the eyes follow you about when you move. BIG BROTHER IS WATCHING YOU, the caption beneath it ran.'''
# Font and colour (best to use fixed-width font)
fnt="lucon.ttf"
textcol=(255,255,255)
# Create image of required dimensions
W,H=1000,1000
im=Image.new("RGB",(W,H))
draw=ImageDraw.Draw(im)
# Search for font size which will fill image with text
nlett=len(text)
nx,ny=0,0
fsize=int(1.5*H)
while nx*ny<nlett:
fsize=fsize-1
font=ImageFont.truetype(fnt, fsize)
# Just get size of one letter
# In fixed-width fonts, all characters are the same size
wint,hint = font.getsize("T")
ny=math.floor(float(H)/float(hint))
nx=math.floor(float(W)/float(wint))
dx=W-(nx*wint)
dy=H-(ny*hint)
# Pad out text so it is centred
x0=int(math.floor(float(dx)/2))
y0=int(math.floor(float(dy)/2))
# Draw text onto image
posx,posy=x0,y0
for letter in text:
if(posx+wint)>W:
posx=x0
posy+=hint
draw.text(xy=(posx,posy),text=letter,fill=textcol,font=font)
posx+=wint
im.save("Text.png")
im.show()