Spaces:
Sleeping
Sleeping
Commit
·
c138b4c
1
Parent(s):
bb96f4c
Modified resize image
Browse files
app.py
CHANGED
|
@@ -435,23 +435,33 @@ def resize_image(image, scaling_factor=1):
|
|
| 435 |
|
| 436 |
def resize_to_square(image, size=1024):
|
| 437 |
|
| 438 |
-
#
|
| 439 |
-
|
| 440 |
-
|
|
|
|
|
|
|
|
|
|
| 441 |
# Resize while maintaining aspect ratio
|
| 442 |
img.thumbnail((size, size), Image.LANCZOS)
|
| 443 |
-
|
| 444 |
# Create a transparent square canvas
|
| 445 |
square_img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
|
| 446 |
-
|
| 447 |
# Calculate the position to paste the resized image (centered)
|
| 448 |
x_offset = (size - img.width) // 2
|
| 449 |
y_offset = (size - img.height) // 2
|
| 450 |
-
|
| 451 |
-
# Paste the resized image onto the square canvas
|
| 452 |
-
square_img.paste(img, (x_offset, y_offset), img)
|
| 453 |
|
| 454 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 455 |
|
| 456 |
|
| 457 |
def encode_image(image):
|
|
|
|
| 435 |
|
| 436 |
def resize_to_square(image, size=1024):
|
| 437 |
|
| 438 |
+
# Load image if a file path is provided
|
| 439 |
+
if isinstance(image_path_or_img, str):
|
| 440 |
+
img = Image.open(image_path_or_img).convert("RGBA")
|
| 441 |
+
else:
|
| 442 |
+
img = image_path_or_img.convert("RGBA") # If already an Image object
|
| 443 |
+
|
| 444 |
# Resize while maintaining aspect ratio
|
| 445 |
img.thumbnail((size, size), Image.LANCZOS)
|
| 446 |
+
|
| 447 |
# Create a transparent square canvas
|
| 448 |
square_img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
|
| 449 |
+
|
| 450 |
# Calculate the position to paste the resized image (centered)
|
| 451 |
x_offset = (size - img.width) // 2
|
| 452 |
y_offset = (size - img.height) // 2
|
|
|
|
|
|
|
|
|
|
| 453 |
|
| 454 |
+
# Extract the alpha channel as a mask
|
| 455 |
+
mask = img.split()[3] if img.mode == "RGBA" else None
|
| 456 |
+
|
| 457 |
+
# Paste the resized image onto the square canvas with the correct transparency mask
|
| 458 |
+
square_img.paste(img, (x_offset, y_offset), mask)
|
| 459 |
+
|
| 460 |
+
# Save if output_path is provided; otherwise, return the PIL Image object
|
| 461 |
+
if output_path:
|
| 462 |
+
square_img.save(output_path, "PNG")
|
| 463 |
+
else:
|
| 464 |
+
return square_img
|
| 465 |
|
| 466 |
|
| 467 |
def encode_image(image):
|