使用 python imagemagick/graphicsmagick 绑定有很大帮助,但不幸的是,并不是所有的功能都在那里。我实际上对@FizxMike 有同样的问题。我需要使用蒙太奇,然后做一些进一步的操作,但是将文件保存在硬盘上,然后将其重新加载到适当的 pgmagick 对象中,以便完成其余操作并再次保存它很慢。
最终我使用了 subprocess 解决方案,但我没有保存在文件中,而是将输出重定向到 stdout。然后,我使用标准输出从 pgmagick.Image 对象中的 pgmagick.Blob 加载图像,并在 python 代码中完成其余的处理。
该过程在代码中如下所示:
import os
import pgmagick
import subprocess
my_files = []
# Dir with the images that you want to operate on
dir_with_images = "."
for file in os.listdir(dir_with_images):
if file.endswith(".png"):
my_files.append(os.path.join(dir_with_images, file))
montage_cmd = ['gm', 'montage']
montage_cmd.extend(my_files)
# The trick is in the next line of code. Instead of saving in a file, e.g. myimage.png
# the montaged file will just be "printed" in the stdout with 'png:-'
montage_cmd.extend(['-tile', '2x2', '-background', 'none', '-geometry', '+0+0', 'png:-'])
# Use the command line 'gm montage' since there are not python bindings for it :(
p = subprocess.Popen(montage_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Get the stdout in a variable
stdout, stderr = p.communicate()
# Load the stdout in a python pgmagick Image object using the pgmagick.Blob
# and do the rest of the editing on python code
img = pgmagick.Image(pgmagick.Blob(stdout))
# Display the image
img.display()
geometry = pgmagick.Geometry(300, 200)
geometry.aspect(True)
# Resize the montaged image to 300x200, but keep the aspect ratio
img.scale(geometry)
# Display it again
img.display()
# And finally save it <- Only once disk access at this point.
img.write('myimage.png')