0

I have a text file which I would like to save as an image, is this possible to do in python?

The textfile is just a regular list of strings such as an essay and I would like to save is as a PNG. I searched Google and stack overflow but to no avail.

4

1 回答 1

0

Getting this to work well, so that the final text is formatted nicely, is not trivial. However here is some code I wrote recently which might get you started:

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()
于 2013-09-20T14:58:26.353 回答