Pillow (the maintained successor to PIL: Python Imaging Library)可以處理你想要的。
您可以在檢索用戶輸入後擴展圖像並放置文本。下面是添加標題的示例:
from PIL import Image, ImageFont, ImageDraw
img = Image.open('my_chart.png')
w,h= img.size
# put pixels into 2D array for ease of use
data = list(img.getdata())
xy_data = []
for y in xrange(h):
temp = []
for x in xrange(w):
temp.append(data[y*w + x])
xy_data.append(temp)
# get the title
title = raw_input("Title:")
# load the font
font_size = 20
font = ImageFont.truetype("/path/to/font.ttf",font_size)
# Get the required height for you images
height_needed = font.getsize(title)[1] + 2 # 2 px for padding
# get the upperleft pixel to match color
bg = xy_data[0][0]
# add rows to the data to prepare for the text
xy_data = [[bg]*w for i in range(height_needed+5)] + xy_data # +5 for more padding
# resize image
img = img.resize((w,h+height_needed+5))
# convert data back to 1D array
data = []
for line in xy_data:
data += line
# put the image back in the data
img.putdata(data)
# get the ImageDraw item for this image
draw = ImageDraw.Draw(img)
# draw the text
draw.text((5,0),title,font=font,fill=(0,0,0)) # fill is black
img.save('titled_plot.png')
似乎是這個腳本的一些問題。我認爲h和w通過腳本被定義爲高度和寬度,以 – moku
@moku啊開頭,對不起,只要將它們改爲'w,h'我會更新我的答案。 –
我改變了他們,並拋出一個錯誤有關ImageFont.py文件: – moku