GIMP3のPython-Fuで選択範囲を別レイヤーに切り出し

コンピュータ

GIMP3.0のPython-Fuの勉強を始めました。
よく使う選択範囲を別レイヤーに切り出すプラグインを作りました。

スクリプト

ファイル名:my-cutp/my-cutp.py

#!/usr/bin/env python3
# 選択範囲を別レイヤーに切り取り
import sys, gi
gi.require_version('Gimp','3.0')
from gi.repository import Gimp
PROC="python-fu-cut-and-paste"
def run(proc, run_mode, image, drawables, config, data):
    if drawables:
        image.undo_group_start()
        try:
            # カット前に、対象レイヤー(複数選択にも対応)へアルファ付与 ---
            for d in drawables:
                # Drawable でも実体が Layer のときだけ対象にする
                if isinstance(d, Gimp.Layer) and not d.has_alpha():
                    d.add_alpha()   # ← アルファ追加
            #drawables[0].invert(False)  # 単純な反転
            target = drawables[0]
            #Gimp.message("1")
            buf = "cut-and-paste-tmp"
            Gimp.edit_named_cut(drawables, buf)  # 選択部があればそこだけ/無ければ全体
            #Gimp.message("2")
            pasted = Gimp.edit_named_paste(target, buf, False)
            new_item = pasted if pasted else None
            # 貼り付け結果がレイヤーの場合もアルファチャンネルを保証しておく ---
            if new_item and isinstance(new_item, Gimp.Layer) and not new_item.has_alpha():
                new_item.add_alpha()
            # 浮動選択ならレイヤー化(既にレイヤーなら何も起きない)
            if new_item:
                try:
                    #Gimp.message("2.5")
                    Gimp.floating_sel_to_layer(new_item)
                except Exception:
                    pass            
            #Gimp.message("3")
            image.undo_group_end()
            return proc.new_return_values(Gimp.PDBStatusType.SUCCESS, None)
        except Exception:
            return proc.new_return_values(Gimp.PDBStatusType.EXECUTION_ERROR, None)
        finally:
            Gimp.buffer_delete(buf)                  # 後始末は常に
            image.undo_group_end()
class Cutp(Gimp.PlugIn):
    def do_query_procedures(self): return [PROC]
    def do_create_procedure(self,name):
        if name!=PROC: return None
        p=Gimp.ImageProcedure.new(self,name,Gimp.PDBProcType.PLUGIN,run,None)
        p.set_menu_label("Cut & Paste")
        p.add_menu_path("<Image>/Filters/My")
        p.set_sensitivity_mask(Gimp.ProcedureSensitivityMask.DRAWABLE)
        return p
Gimp.main(Cutp.__gtype__, sys.argv)

プラグインの保存場所

C:\Users\ユーザー名\AppData\Roaming\GIMP\3.0

こちらにスクリプト名と同名のディレクトリ(my-cutp)を作成し、そこにスクリプト(my-cutp.py)を保存しました。

Windows版のお話です。LinuxやmacOSの場合は保存するプラグインディレクトリが異なりますし、スクリプトに実行属性をつける必要があります。

コメント