I’ve written a script that converts a directory of images and a directory of auto-generated masks into .kra files so the masks can be easily tweaked. I couldn’t get the script to create the files from scratch so I fell back to setPixelData on the template layers. Looking for feedback.
print('-- SCRIPT BEGIN --')
from contextlib import closing, suppress
from pathlib import Path
import shutil
from typing import Final
from PIL import Image
from PyKrita.krita import Krita
ROOT_DIR: Final = Path(__file__).resolve().parent
TEMPLATE_PATH: Final = ROOT_DIR / 'template.kra'
def create_path(dir_name: str, stem: str, suffix: str) -> Path:
return (ROOT_DIR / dir_name / stem).with_suffix(suffix)
def create_kra(krita: Krita, image_path: Path):
image_stem = image_path.stem
r, g, b, a = Image.open(image_path).convert('RGBA').split()
image = Image.merge('RGBA', [b, g, r, a])
mask_path = create_path('maskes', image_stem, '.png')
mask = Image.open(mask_path).convert('L')
size = (0, 0, image.width, image.height)
with closing(krita.openDocument(str(TEMPLATE_PATH))) as document:
document.resizeImage(*size)
for name, pil_image in [('Image', image), ('Mask', mask)]:
document.nodeByName(name).setPixelData(pil_image.tobytes(), *size)
kra_path = create_path('kra', image_stem, '.kra')
document.saveAs(str(kra_path))
def main(argv: list[str]) -> None:
kra_dir = ROOT_DIR / 'kra'
with suppress(FileNotFoundError):
shutil.rmtree(kra_dir)
kra_dir.mkdir()
krita = Krita.instance()
for image_path in (ROOT_DIR / 'originals').iterdir():
print('Creating .kra for', image_path.stem)
create_kra(krita, image_path)
print()
print('-- SCRIPT END -- ')