Skip to content

Instantly share code, notes, and snippets.

@skarfie123
Created December 31, 2024 13:02
Show Gist options
  • Select an option

  • Save skarfie123/90e86a7a657b51f4702d3d09c119c885 to your computer and use it in GitHub Desktop.

Select an option

Save skarfie123/90e86a7a657b51f4702d3d09c119c885 to your computer and use it in GitHub Desktop.
I asked ChatGPT to write this script to make square images for Instagram
import sys
import os
from PIL import Image, ImageOps, ImageFilter
# Define constants
SQUARE_SUFFIX = "_square" # Suffix for the output files
BLUR_AMOUNT = 100 # Amount of blur for the background
def delete_previous_square_images(folder):
"""Delete all images with the defined suffix in their filename."""
for filename in os.listdir(folder):
if SQUARE_SUFFIX in filename.lower():
file_path = os.path.join(folder, filename)
try:
os.remove(file_path)
print(f"Deleted previous square image: {file_path}")
except Exception as e:
print(f"Error deleting {file_path}: {e}")
def create_square_with_background(image):
"""Create a square image with a blurred black-and-white version of the image as the background."""
# Apply EXIF orientation
image = ImageOps.exif_transpose(image)
# Determine the larger size for the square
square_size = max(image.width, image.height)
# Create a grayscale version of the image
grayscale_background = image.convert("L").convert("RGB")
# Resize the background to fill the square size
background = ImageOps.fit(grayscale_background, (square_size, square_size))
# Apply a blur filter to the background
background = background.filter(ImageFilter.GaussianBlur(BLUR_AMOUNT))
# Resize the original image to fit within the square while maintaining aspect ratio
foreground = ImageOps.contain(image, (square_size, square_size))
# Create a new image with the same size as the background and paste the foreground onto it
square_image = background.copy()
foreground_position = (
(square_size - foreground.width) // 2,
(square_size - foreground.height) // 2,
)
square_image.paste(foreground, foreground_position)
return square_image
def main():
if len(sys.argv) < 2:
print(f"Usage: python {sys.argv[0]} <input_folder>")
sys.exit(1)
# Get the input folder path from CLI
input_folder = sys.argv[1]
if not os.path.isdir(input_folder):
print(f"Error: The provided path '{input_folder}' is not a directory.")
sys.exit(1)
# Create a subfolder for square images
square_folder = os.path.join(input_folder, "square")
os.makedirs(square_folder, exist_ok=True)
# Delete previous '_square' images in the square folder
delete_previous_square_images(square_folder)
# Process each image in the input folder
for filename in os.listdir(input_folder):
if filename.lower().endswith(("png", "jpg", "jpeg", "bmp", "gif")):
input_path = os.path.join(input_folder, filename)
# Generate the new filename with the defined suffix
name, ext = os.path.splitext(filename)
output_path = os.path.join(square_folder, f"{name}{SQUARE_SUFFIX}{ext}")
try:
with Image.open(input_path) as img:
# Create square image
square_img = create_square_with_background(img)
# Save the image
square_img.save(output_path)
print(f"Processed and saved: {output_path}")
except Exception as e:
print(f"Error processing {filename}: {e}")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment