Gimp Python 脚本单独工作,但组合时不工作

Gimp Python scripts work separately but not when combined

我有一个多层 Gimp XCF 模板,我的目标是自动将 JPG 插入其中并从命令行导出它们。

我有第一个工作的 python-fu 插件用于插入图像,第二个工作的 python-fu 插件用于 flattening/saving 图像(一行执行代码) ,但我想结合这两个插件,使它们更容易从命令行调用。最后我还想自动打开 XCF 文件。现在虽然我只是想结合这两个功能。两个插件都接收“图像”和“图层”作为输入参数。

我的组合插件的函数参数是图像、图层、要插入的 JPG(文件)、用于将图像放置在 XCF 模板中的 X 和 Y 偏移量(x_offset、y_offset) ,以及导出位置 (outputFolder)。

当我将保存命令(pdb.file_jpeg_save 显示在我的代码底部附近)添加到第一个工作脚本时,它失败了。为什么它自己可以工作但在这里失败了?

我的代码如下所示。

#!/usr/bin/env python

from gimpfu import *

def add_flatten_save(image, layer, file, x_offset, y_offset, outputFolder):
    ''' Add image to new layer, flatten, then saveSave the current layer into a PNG file, a JPEG file and a BMP file. '''

    # Indicates that the process has started.
    gimp.progress_init("Opening '" + file + "'...")

    try:
        # Open file.
        fileImage = None

        if(file.lower().endswith(('.jpeg', '.jpg'))):
            fileImage = pdb.file_jpeg_load(file, file)

            # Create new layer.
            newLayer = gimp.Layer(image, "New Layer Name", layer.width, layer.height, layer.type, layer.opacity, layer.mode)
            # the +1 adds it behind the top layer
            image.add_layer(newLayer, +1)

            # Put image into the new layer.
            fileLayer = fileImage.layers[0]
            pdb.gimp_edit_copy(fileLayer)
            floating = pdb.gimp_edit_paste(newLayer, True)

            # Update the new layer.
            newLayer.flush()
            newLayer.merge_shadow(True)
            newLayer.update(0, 0, newLayer.width, newLayer.height)

            # Flatten + offset floating layer, then flatten image
            pdb.gimp_floating_sel_to_layer(floating)
            pdb.gimp_layer_set_offsets(floating, x_offset, y_offset)
            pdb.gimp_image_flatten(image)

            # Export JPG of flattened image
            pdb.file_jpeg_save(image, layer, outputFolder + "/" + layer.name + ".jpg", "raw_filename", 0.9, 0, 0, 0, "Creating with GIMP", 0, 0, 0, 0)

        else:
            gimp.message("The image could not be opened since it is not an image file.")

    except Exception as err:
        gimp.message("Unexpected error: " + str(err))
    
register(
    "python_fu_add_flatten_save",
    "Add image to layer",
    "Add image to layer and flatten.",
    "Tim B.",
    "Tim B.",
    "2021",
    "<Image>/Filters/Tim/Add, flatten, save",
    "*",
    [
        (PF_FILE, "file", "File to open", ""),
        (PF_INT, "x_offset", "X offset", ""),
        (PF_INT, "y_offset", "Y offset", ""),
        (PF_DIRNAME, "outputFolder", "Output directory", ""),
    ],
    [],
    add_flatten_save)

main()

根本问题是,当您将图像展平时,图层“layer”不再存在。

尝试在保存之前添加 layer = pdb.gimp_image_get_active_layer(image)