使用 Python 自动化 PNG 格式转换

4

我正在尝试寻找一种自动化格式化PNG图像的方法,以添加标题、副标题和带有标志图像和来源的页脚栏。由于我对Python语言最为熟悉,因此希望使用Python进行图像格式化。请问在这种情况下应该使用哪些模块?理想情况下,脚本的使用者会按照以下步骤进行操作:

1) 使用者将拥有一个PNG图像,其外观类似于下面的示例:

enter image description here

2) 使用者将启动脚本:

python autochart_formatting.py

3) 脚本会要求用户提供以下信息:

  • 输入图表标题:
  • 输入图表副标题:
  • 输入来源:
  • 调查名称:
  • 样本 n=:
  • 输入您想要格式化的图表 png 的路径:
  • 输入您想要保存格式化图像的路径:

3) 有了这些信息,png 图像将被格式化为如下所示:

enter image description here

2个回答

1

Pillow(Python图像处理库的维护继承者)可以完全处理您想要的内容。

您可以在检索用户输入后扩展图像并放置文本。以下是添加标题的示例:

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
追踪(Traceback)最近的调用(most recent call): 文件 "HubbleFormatter.py",第20行,在<module>中: font = ImageFont.truetype("/Users/kyle/Destop/GothamFonts/GOTHMBOK.ttf",font_size) 文件 "/usr/local/lib/python2.7/site-packages/PIL/ImageFont.py",第262行,truetype函数: return FreeTypeFont(font, size, index, encoding) 文件 "/usr/local/lib/python2.7/site-packages/PIL/ImageFont.py",第142行,__init__函数: self.font = core.getfont(font, size, index, encoding) IOError: 无法打开资源 - moku
@moku 我刚才进行了一次编辑,已经修复了这个问题。请确保调整大小的代码行参数是一个元组,应该是:img = img.resize( (w,h+height_needed+5) ) - Farmer Joe
@moku 我又做了一次编辑,包括重新添加数据,这是我忘记的关键步骤,你应该再次检查我的帖子。PIL很棒!我喜欢使用它,它是我处理图像的首选。如果你想了解有关该库的其他信息,请告诉我! - Farmer Joe
@moku 当然,随时欢迎,我很乐意帮忙! - Farmer Joe
显示剩余6条评论

0

这些都可以轻松实现,使用Pillow (Python Imaging Library的一个分支,目前仍在维护中)。

如果您不想自己编写图形代码,也可以使用matplotlib。它在格式化图形方面可能会略有限制,但创建速度更快。


好的,我会去看看Pillow。Matplotlib也是一个可能性,但并不是每个人都有那种技能。一些图表图像将来自Excel,并保存为png格式,需要按照这种方式进行格式化。Pillow如何处理导入的png文件的大小差异?这会很麻烦吗?还是应该只有3种标准图像尺寸,以简化事情? - moku
我明白了 - 从你的问题中我没有理解到你只是修改图表 - 我以为你是从头开始创建它们。在这种情况下,是的,你需要Pillow而不是matplotlib。Pillow是一个通用的图像处理模块,因此非常灵活。 - Brionius
Pillow非常擅长调整图像大小,如果这就是你的意思。如果你想知道如何在图表大小不同的情况下添加标题...除非你更具体地描述限制条件,否则我不能帮助你。 - Brionius
我认为我只需要到那时再去跨越那座桥,然后深入了解Pillow并看看它能做什么! - moku

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接