Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save skeptrunedev/bd6298aa8bb80a94eaedf25676c924dd to your computer and use it in GitHub Desktop.

Select an option

Save skeptrunedev/bd6298aa8bb80a94eaedf25676c924dd to your computer and use it in GitHub Desktop.
Stitch image collection into gif
from PIL import Image
import os
import glob
def create_rotating_gif(
folder_path, output_path="rotating_animation.gif", duration=500
):
"""
Create a GIF from images in a folder
Args:
folder_path: Path to folder containing images
output_path: Output GIF file path
duration: Duration between frames in milliseconds
"""
# Get all image files (common formats)
image_extensions = ["*.jpg", "*.jpeg", "*.png", "*.bmp"]
image_files = []
for extension in image_extensions:
image_files.extend(glob.glob(os.path.join(folder_path, extension)))
image_files.extend(glob.glob(os.path.join(folder_path, extension.upper())))
# Sort files naturally
image_files.sort()
if not image_files:
print("No images found in the specified folder!")
return
# Load and process images
frames = []
for image_file in image_files:
try:
img = Image.open(image_file)
# Convert to RGB if necessary
if img.mode != "RGB":
img = img.convert("RGB")
# Optional: Resize images to consistent size
img = img.resize((300, 400), Image.ANTIALIAS)
frames.append(img)
print(f"Added: {os.path.basename(image_file)}")
except Exception as e:
print(f"Error loading {image_file}: {e}")
if frames:
# Save as GIF
frames[0].save(
output_path,
save_all=True,
append_images=frames[1:],
duration=duration,
loop=0, # 0 means infinite loop
)
print(f"GIF created: {output_path}")
else:
print("No valid images to process!")
# Usage
folder_path = "." # Change this to your folder path
create_rotating_gif(folder_path, "my_animation.gif", duration=400)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment