"""Generic image utilities for ComfyUI.""" import os import json import re import threading import time import uuid from collections import OrderedDict from pathlib import Path from PIL import Image import folder_paths _IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif", ".tif", ".tiff"} _SERVE_TOKENS = OrderedDict() _SAVE_COUNTER_LOCK = threading.Lock() def resolve_serve_token(token): return _SERVE_TOKENS.get(str(token or "")) def _folder_is_image(name): return Path(str(name)).suffix.lower() in _IMAGE_EXTENSIONS def _list_folder_image_files(real_folder, recursive=False): root = Path(real_folder) paths = root.rglob("*") if recursive else root.glob("*") files = [] for path in paths: if path.is_file() and _folder_is_image(path.name): files.append({ "file": str(path.relative_to(root)).replace(os.sep, "/"), "mtime": path.stat().st_mtime, }) return sorted(files, key=lambda item: item["file"].lower()) def _next_counter_for_relative_path(base_directory, relative_template): relative_template = str(relative_template).replace("\\", "/") if "%counter%" not in relative_template: return 1 base = Path(base_directory) if not base.exists(): return 1 pattern = re.compile( re.escape(relative_template).replace(re.escape("%counter%"), r"(\d+)") ) highest = 0 for path in base.rglob("*"): if not path.is_file(): continue relative_path = path.relative_to(base).as_posix() match = pattern.fullmatch(relative_path) if match: highest = max(highest, int(match.group(1))) return highest + 1 def _next_available_relative_path(base_directory, relative_path): """Return a collision-free relative path, adding a counter when needed.""" relative_path = str(relative_path).replace("\\", "/") if "%counter%" in relative_path: counter = _next_counter_for_relative_path(base_directory, relative_path) return relative_path.replace("%counter%", str(counter).zfill(3)) candidate = Path(base_directory) / Path(relative_path) if not candidate.exists(): return relative_path path = Path(relative_path) suffix = path.suffix name = path.name[:-len(suffix)] if suffix else path.name counter_template = str(path.with_name(f"{name}_%counter%{suffix}")).replace("\\", "/") counter = _next_counter_for_relative_path(base_directory, counter_template) return counter_template.replace("%counter%", str(counter).zfill(3)) def _image_to_pil(image): array = image.detach().cpu().numpy() if hasattr(image, "detach") else image.cpu().numpy() array = (array[..., :3].clip(0, 1) * 255).astype("uint8") return Image.fromarray(array) def _is_within_directory(parent, child): try: return os.path.commonpath([os.path.realpath(parent), os.path.realpath(child)]) == os.path.realpath(parent) except ValueError: return False def _build_pnginfo(prompt=None, extra_pnginfo=None): if not prompt and not extra_pnginfo: return None from PIL.PngImagePlugin import PngInfo info = PngInfo() if prompt is not None: info.add_text("prompt", json.dumps(prompt, ensure_ascii=False)) for key, value in (extra_pnginfo or {}).items(): info.add_text(str(key), json.dumps(value, ensure_ascii=False)) return info class DumasImageCompareNode: @classmethod def INPUT_TYPES(cls): return {"optional": {"image1": ("IMAGE",), "image2": ("IMAGE",)}} RETURN_TYPES = ("IMAGE",) RETURN_NAMES = ("result",) FUNCTION = "compare_images" CATEGORY = "Dumas/Image" OUTPUT_NODE = True def compare_images(self, image1=None, image2=None): images = [] for slot, image in enumerate((image1, image2), 1): if image is None: continue # The compare viewer can be used by several executions at once. # Fixed filenames caused one run to replace another run's preview. path = Path(folder_paths.get_temp_directory()) / f"dumas_compare_{uuid.uuid4().hex}_{slot}.png" path.parent.mkdir(parents=True, exist_ok=True) _image_to_pil(image[0]).save(path) images.append({"filename": path.name, "subfolder": "", "type": "temp", "slot": slot}) # Tensors cannot be used as Python booleans when they contain more # than one value. Select the second slot by presence explicitly. result = image2 if image2 is not None else image1 return {"ui": {"images": images}, "result": (result,)} class DumasSaveImageNode: DESCRIPTION = "Save image batches with collision-safe names and ComfyUI previews." @classmethod def INPUT_TYPES(cls): return { "required": { "images": ("IMAGE",), "folder": ("STRING", {"default": ""}), "pattern": ("STRING", {"default": "image_%counter%"}), "format": (["png", "jpg", "webp"], {"default": "png"}), "quality": ("INT", {"default": 95, "min": 1, "max": 100}), "embed_workflow": ("BOOLEAN", {"default": True}), "save_on_run": ("BOOLEAN", {"default": True}), }, "optional": {"name": ("STRING", {"default": ""}), "name_2": ("STRING", {"default": ""})}, "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"}, } @classmethod def IS_CHANGED(cls, **_kwargs): return float("nan") RETURN_TYPES = ("IMAGE", "STRING", "STRING") RETURN_NAMES = ("image", "folder", "filename") # A batch can produce more than one filename; keep the image batch and # folder scalar while exposing the generated names as a STRING list. OUTPUT_IS_LIST = (False, False, True) FUNCTION = "save_images" CATEGORY = "Dumas/Image" OUTPUT_NODE = True def save_images(self, images, folder, pattern, format, quality, embed_workflow, save_on_run, name="", name_2="", prompt=None, extra_pnginfo=None, **_kwargs): if not save_on_run: # Match the preview/save split used by Pixaroma: Preview mode must # still produce visible, temporary images, but must not write to # the selected destination folder. temp_dir = Path(folder_paths.get_temp_directory()).resolve() temp_dir.mkdir(parents=True, exist_ok=True) preview_images = [] preview_format = str(format or "png").lower() extension = ".jpg" if preview_format == "jpg" else ( ".webp" if preview_format == "webp" else ".png" ) for index, image in enumerate(images): path = temp_dir / f"dumas_save_preview_{uuid.uuid4().hex}{extension}" pil = _image_to_pil(image) if preview_format == "jpg": pil.convert("RGB").save(path, "JPEG", quality=max(1, min(100, int(quality)))) elif preview_format == "webp": pil.save(path, "WEBP", quality=max(1, min(100, int(quality)))) else: pil.save(path, "PNG", pnginfo=_build_pnginfo(prompt, extra_pnginfo) if embed_workflow else None) preview_images.append({"filename": path.name, "subfolder": "", "type": "temp"}) return { "ui": {"images": preview_images}, "result": (images, str(temp_dir), [item["filename"] for item in preview_images]), } output_dir = Path(folder_paths.get_output_directory()).resolve() base = Path(folder).expanduser().resolve() if str(folder or "").strip() else output_dir base.mkdir(parents=True, exist_ok=True) ui_images = [] extension = ".jpg" if format == "jpg" else f".{format}" # Counter selection and the corresponding writes must be one critical # section. Without this, overlapping ComfyUI executions can both see # the same highest existing counter and overwrite one another. with _SAVE_COUNTER_LOCK: for index, image in enumerate(images): width, height = int(image.shape[2]), int(image.shape[1]) stem = str(pattern or "image_%counter%") stem = stem.replace("%input%", _safe_token(name)).replace("%input2%", _safe_token(name_2)) stem = stem.replace("%width%", str(width)).replace("%height%", str(height)).replace("%batch_num%", str(index)) relative = stem.replace("\\", "/") + extension relative = _next_available_relative_path(str(base), relative) path = base / Path(relative) path.parent.mkdir(parents=True, exist_ok=True) pil = _image_to_pil(image) if format == "jpg": pil.convert("RGB").save(path, "JPEG", quality=max(1, min(100, int(quality)))) elif format == "webp": pil.save(path, "WEBP", quality=max(1, min(100, int(quality)))) else: pil.save(path, "PNG", pnginfo=_build_pnginfo(prompt, extra_pnginfo) if embed_workflow else None) if _is_within_directory(str(output_dir), str(path)): subfolder = str(path.parent.relative_to(output_dir)).replace(os.sep, "/") ui_images.append({"filename": path.name, "subfolder": "" if subfolder == "." else subfolder, "type": "output"}) else: token = uuid.uuid4().hex _SERVE_TOKENS[token] = str(path) ui_images.append({"filename": path.name, "subfolder": str(path.parent).replace(os.sep, "/"), "type": "external", "token": token}) return { "ui": {"images": ui_images}, "result": (images, str(base), [item["filename"] for item in ui_images]), } def _safe_token(value): return re.sub(r"[^A-Za-z0-9_.-]+", "_", Path(str(value or "")).stem).strip("._") class DumasLoadImagesFolderNode: @classmethod def INPUT_TYPES(cls): # The browser UI stores its complete selection in this hidden input. # Keep an optional folder for old workflows which used the original # single-folder widget before the Pixaroma-style picker was added. return { "optional": {"folder": ("STRING", {"default": ""})}, "hidden": {"LoadImagesFolderState": ("STRING", {"default": ""})}, } RETURN_TYPES = ("IMAGE", "MASK", "INT", "INT", "STRING", "INT", "INT", "STRING") RETURN_NAMES = ("image", "mask", "width", "height", "filename", "index", "total", "path") OUTPUT_IS_LIST = (True, True, True, True, True, True, True, True) FUNCTION = "load" CATEGORY = "Dumas/Image" def load(self, folder="", LoadImagesFolderState="", **_kwargs): state = {} if LoadImagesFolderState: try: state = json.loads(LoadImagesFolderState) except (TypeError, ValueError): state = {} selected_folder = str(state.get("folder") or folder or "").strip() root = Path(selected_folder).expanduser() if not root.is_dir(): raise ValueError("Selected image folder does not exist.") recursive = bool(state.get("recursive", False)) candidates = [Path(item["file"]) for item in _list_folder_image_files(str(root), recursive)] by_relative = {path.as_posix(): path for path in candidates} selected = [str(value).replace("\\", "/") for value in (state.get("selected") or [])] mode = str(state.get("selection_mode") or "selected") if state: if mode == "all": relative_files = [path.as_posix() for path in candidates] elif mode == "first_n": try: count = max(0, int(state.get("first_n", 0))) except (TypeError, ValueError): count = 0 relative_files = [path.as_posix() for path in candidates[:count]] elif mode == "random": import random relative_files = [random.choice([path.as_posix() for path in candidates])] if candidates else [] else: relative_files = [value for value in selected if value in by_relative] else: # Legacy workflows without the hidden state load the whole folder. relative_files = [path.as_posix() for path in candidates] if not relative_files: raise ValueError("No images selected in the folder.") sort_name = str(state.get("sort") or "name") reverse = str(state.get("sort_dir") or "asc").lower() == "desc" if sort_name == "date": relative_files.sort(key=lambda name: (root / name).stat().st_mtime, reverse=reverse) else: relative_files.sort(key=str.lower, reverse=reverse) import numpy as np import torch images, masks, widths, heights, names, indexes, totals, paths = [], [], [], [], [], [], [], [] total = len(relative_files) for index, relative in enumerate(relative_files): path = (root / relative).resolve() if not _is_within_directory(root, path) or not path.is_file(): continue with Image.open(path) as source: source = source.convert("RGBA") rgba = np.asarray(source).astype("float32") / 255.0 image = torch.from_numpy(rgba[..., :3].copy())[None, ...] mask = torch.from_numpy((1.0 - rgba[..., 3]).copy()) images.append(image) masks.append(mask) widths.append(int(source.width)) heights.append(int(source.height)) names.append(path.name) indexes.append(index) totals.append(total) paths.append(str(path)) if not images: raise ValueError("No readable images were found in the selected folder.") return images, masks, widths, heights, names, indexes, totals, paths NODE_CLASS_MAPPINGS = { "DumasImageCompare": DumasImageCompareNode, "DumasSaveImage": DumasSaveImageNode, "DumasLoadImagesFolder": DumasLoadImagesFolderNode, } NODE_DISPLAY_NAME_MAPPINGS = { "DumasImageCompare": "Dumas Image Compare", "DumasSaveImage": "Save Image Dumas", "DumasLoadImagesFolder": "Load Images from Folder Dumas", }