"""Generic image utilities for ComfyUI.""" import os import json import re 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() 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): template = str(relative_template).replace("%counter%", "*") parent = Path(base_directory) / Path(template).parent stem = Path(template).name if not parent.exists(): return 1 pattern = re.compile(re.escape(stem).replace(r"\*", r"(\d+)") + r"(?:\.[^.]+)?$") highest = 0 for path in parent.iterdir(): match = pattern.match(path.name) if match: highest = max(highest, int(match.group(1))) return highest + 1 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}" 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 counter = _next_counter_for_relative_path(str(base), relative) relative = relative.replace("%counter%", str(counter).zfill(3)) 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", }