"""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("*") return sorted(str(path.relative_to(root)).replace(os.sep, "/") for path in paths if path.is_file() and _folder_is_image(path.name)) 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 path = Path(folder_paths.get_temp_directory()) / f"dumas_compare_{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}) return {"ui": {"images": images}, "result": (image2 or image1,)} 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 = () 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: return {"ui": {"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}} 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): return {"required": {"folder": ("STRING", {"default": ""})}} RETURN_TYPES = ("IMAGE", "MASK", "INT", "INT", "STRING", "INT", "INT") RETURN_NAMES = ("image", "mask", "width", "height", "filename", "index", "total") FUNCTION = "load" CATEGORY = "Dumas/Image" def load(self, folder): files = sorted(path for path in Path(folder).iterdir() if path.suffix.lower() in _IMAGE_EXTENSIONS) if folder and Path(folder).is_dir() else [] if not files: raise ValueError("No image files found in the selected folder.") image = Image.open(files[0]).convert("RGB") import torch import numpy as np tensor = torch.from_numpy(np.asarray(image).astype("float32") / 255.0)[None, ...] height, width = image.height, image.width mask = torch.zeros((1, height, width), dtype=torch.float32) return tensor, mask, width, height, files[0].name, 0, len(files) 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", }