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

问题描述

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

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

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

当我将保存命令(显示代码底部附近的@H_404[email protected]_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,newLayer.width,newLayer.height)

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

            # Export JPG of flattened image
            pdb.file_jpeg_save(image,outputFolder + "/" + layer.name + ".jpg","raw_filename",0.9,"Creating with GIMP",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.","2021","<Image>/Filters/Tim/Add,save","*",[
        (PF_FILE,"file","File to open",""),(PF_INT,"x_offset","X offset","y_offset","Y offset",(PF_DIRNAME,"outputFolder","Output directory",],[],add_flatten_save)

main()

解决方法

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

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