Skip to content

Commit ae0e7c4

Browse files
Resize and pad image node. (Comfy-Org#8636)
1 parent 78f7926 commit ae0e7c4

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

comfy_extras/nodes_images.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,62 @@ def stitch(
414414
concat_dim = 2 if direction in ["left", "right"] else 1
415415
return (torch.cat(images, dim=concat_dim),)
416416

417+
class ResizeAndPadImage:
418+
@classmethod
419+
def INPUT_TYPES(cls):
420+
return {
421+
"required": {
422+
"image": ("IMAGE",),
423+
"target_width": ("INT", {
424+
"default": 512,
425+
"min": 1,
426+
"max": MAX_RESOLUTION,
427+
"step": 1
428+
}),
429+
"target_height": ("INT", {
430+
"default": 512,
431+
"min": 1,
432+
"max": MAX_RESOLUTION,
433+
"step": 1
434+
}),
435+
"padding_color": (["white", "black"],),
436+
"interpolation": (["area", "bicubic", "nearest-exact", "bilinear", "lanczos"],),
437+
}
438+
}
439+
440+
RETURN_TYPES = ("IMAGE",)
441+
FUNCTION = "resize_and_pad"
442+
CATEGORY = "image/transform"
443+
444+
def resize_and_pad(self, image, target_width, target_height, padding_color, interpolation):
445+
batch_size, orig_height, orig_width, channels = image.shape
446+
447+
scale_w = target_width / orig_width
448+
scale_h = target_height / orig_height
449+
scale = min(scale_w, scale_h)
450+
451+
new_width = int(orig_width * scale)
452+
new_height = int(orig_height * scale)
453+
454+
image_permuted = image.permute(0, 3, 1, 2)
455+
456+
resized = comfy.utils.common_upscale(image_permuted, new_width, new_height, interpolation, "disabled")
457+
458+
pad_value = 0.0 if padding_color == "black" else 1.0
459+
padded = torch.full(
460+
(batch_size, channels, target_height, target_width),
461+
pad_value,
462+
dtype=image.dtype,
463+
device=image.device
464+
)
465+
466+
y_offset = (target_height - new_height) // 2
467+
x_offset = (target_width - new_width) // 2
468+
469+
padded[:, :, y_offset:y_offset + new_height, x_offset:x_offset + new_width] = resized
470+
471+
output = padded.permute(0, 2, 3, 1)
472+
return (output,)
417473

418474
class SaveSVGNode:
419475
"""
@@ -536,5 +592,6 @@ def get_size(self, image, unique_id=None) -> tuple[int, int]:
536592
"SaveAnimatedPNG": SaveAnimatedPNG,
537593
"SaveSVGNode": SaveSVGNode,
538594
"ImageStitch": ImageStitch,
595+
"ResizeAndPadImage": ResizeAndPadImage,
539596
"GetImageSize": GetImageSize,
540597
}

0 commit comments

Comments
 (0)