Skip to content

Commit 6ee278a

Browse files
committed
ImageResizeKJv2: Add total_pixels mode
Resizes to desired total pixel count while preserving aspect ratio
1 parent 0797150 commit 6ee278a

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

nodes/image_nodes.py

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2468,7 +2468,7 @@ def INPUT_TYPES(s):
24682468
"width": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1, }),
24692469
"height": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1, }),
24702470
"upscale_method": (s.upscale_methods,),
2471-
"keep_proportion": (["stretch", "resize", "pad", "pad_edge", "pad_edge_pixel", "crop", "pillarbox_blur"], { "default": False }),
2471+
"keep_proportion": (["stretch", "resize", "pad", "pad_edge", "pad_edge_pixel", "crop", "pillarbox_blur", "total_pixels"], { "default": False }),
24722472
"pad_color": ("STRING", { "default": "0, 0, 0", "tooltip": "Color to use for padding."}),
24732473
"crop_position": (["center", "top", "bottom", "left", "right"], { "default": "center" }),
24742474
"divisible_by": ("INT", { "default": 2, "min": 0, "max": 512, "step": 1, }),
@@ -2505,19 +2505,23 @@ def resize(self, image, width, height, keep_proportion, upscale_method, divisibl
25052505
else:
25062506
device = torch.device("cpu")
25072507

2508-
if width == 0:
2509-
width = W
2510-
if height == 0:
2511-
height = H
2512-
25132508
pillarbox_blur = keep_proportion == "pillarbox_blur"
25142509

25152510
# Initialize padding variables
25162511
pad_left = pad_right = pad_top = pad_bottom = 0
2517-
2518-
if keep_proportion == "resize" or keep_proportion.startswith("pad") or pillarbox_blur:
2512+
2513+
if keep_proportion in ["resize", "total_pixels"] or keep_proportion.startswith("pad") or pillarbox_blur:
2514+
if keep_proportion == "total_pixels":
2515+
total_pixels = width * height
2516+
aspect_ratio = W / H
2517+
new_height = int(math.sqrt(total_pixels / aspect_ratio))
2518+
new_width = int(math.sqrt(total_pixels * aspect_ratio))
2519+
25192520
# If one of the dimensions is zero, calculate it to maintain the aspect ratio
2520-
if width == 0 and height != 0:
2521+
elif width == 0 and height == 0:
2522+
new_width = W
2523+
new_height = H
2524+
elif width == 0 and height != 0:
25212525
ratio = height / H
25222526
new_width = round(W * ratio)
25232527
new_height = height
@@ -2563,6 +2567,11 @@ def resize(self, image, width, height, keep_proportion, upscale_method, divisibl
25632567

25642568
width = new_width
25652569
height = new_height
2570+
else:
2571+
if width == 0:
2572+
width = W
2573+
if height == 0:
2574+
height = H
25662575

25672576
if divisible_by > 1:
25682577
width = width - (width % divisible_by)

0 commit comments

Comments
 (0)