2019年5月13日月曜日

KritaのPythonで指定フォルダと同じ階層のファイルを作ってみた

ペイントソフトのKritaがPythonのスクリプトに対応しているのは以前も話題にしましたが、
改めて調べていて練習代わりに 選択したフォルダの下の階層を再現して画像を読み込むスクリプトを作ったのでメモ

メニューのツール>Scripts>Scripter で出るウィンドウにコピペして再生ボタンを押すことで実行できます。
実行すると表示されるファイル選択ダイアログで フォルダを指定できます

from krita import *
from PyQt5 import QtWidgets

import os
from pathlib import Path

#Shoose directory
work_dir = QtWidgets.QFileDialog.getExistingDirectory()
#filepath as object
work_path = Path( work_dir )

def add_document_to_window():
    """Add new document to Krita
    Arguments:
        width (int): width in pixels
        height (int): height in pixels
        name (str): name of the image (not the filename of the document)
        colorModel (str): color model of document, e.g. "RGBA", "XYZA", "LABA", "CMYKA", "GRAYA", "YCbCrA"
        colorDepth (str): color depth, e.g. "U8", "U16", "F16" or "F32"
        profile (str): The name of an icc profile that is known to Krita
        resolution (float): the resolution in points per inch
        
    Returns:
        the created document
    
    """
    doc = Krita().createDocument(100, 100, "Test", "RGBA", "U8", "", 72.0)
    Application.activeWindow().addView(doc)
    return doc
#make PSDFile
def load_image_as_layer(parent_node,
                        directory_path,
                        extension_list= ["png","JPG","bmp"] ):
        """load imagedata on parent_node"""
        img_list = []
        #get image file
        for ext in extension_list:
            img_list += list( directory_path.glob("*." + ext))
        for file_path in img_list:
            if not file_path.exists():pass
            new_doc = Krita().openDocument(os.fspath(file_path))
            image_node = new_doc.rootNode().childNodes()[0]
            parent_node.addChildNode(image_node.clone(),None)
            new_child = parent_node.childNodes()[-1]
            new_child.setName(file_path.name)
            #fit document to image
            if new_child.bounds().width()> doc.width():
                doc.setWidth(new_child.bounds().width())
            if new_child.bounds().height()> doc.height():
                doc.setHeight(new_child.bounds().height())
            new_doc.close()
            
            

def createGroupLayer_recursively(path_object,node):
        """make GroupLayer like directory"""
        dir_list = [x for x in path_object.iterdir() if x.is_dir()]
        doc = Krita().activeDocument()
        Grouplayers = [doc.createGroupLayer(p.name) for p in dir_list]
        node.setChildNodes( reversed(Grouplayers) )
        load_image_as_layer(node,path_object)
        for childNode in Grouplayers:
            #get chld directory
            dir = path_object/childNode.name()
            createGroupLayer_recursively(dir,childNode)
        

doc = add_document_to_window()
doc_root = doc.rootNode()
#Scan the directory structure recursively
createGroupLayer_recursively(work_path,doc_root)
doc.refreshProjection()#ドキュメントの表示状態の更新



Kritaは独自ファイルのほか、PSDでの保存もできるので色々使い道はあるかと思います