Created
March 2, 2025 19:50
-
-
Save chriscarrollsmith/de06275be205b3fd00be9761cd1d681b to your computer and use it in GitHub Desktop.
Python script to create an animated gif
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PIL import Image | |
import os | |
def create_gif(image_folder, gif_name, frame_duration=200): | |
""" | |
Creates an animated GIF from images in a folder. | |
Args: | |
image_folder (str): Path to the folder containing the images. | |
gif_name (str): Name of the output GIF file. | |
frame_duration (int, optional): Duration of each frame in milliseconds. Defaults to 200. | |
""" | |
images = [] | |
filenames = sorted(os.listdir(image_folder)) | |
for filename in filenames: | |
if filename.lower().endswith(('.png', '.jpg', '.jpeg')): | |
img_path = os.path.join(image_folder, filename) | |
try: | |
img = Image.open(img_path) | |
images.append(img) | |
except FileNotFoundError: | |
print(f"Error: Image file not found: {img_path}") | |
return | |
except Exception as e: | |
print(f"Error opening image {filename}: {e}") | |
return | |
if images: | |
images[0].save(gif_name, save_all=True, append_images=images[1:], duration=frame_duration, loop=0) | |
print(f"Successfully created GIF: {gif_name}") | |
else: | |
print("No valid images found in the specified folder.") | |
if __name__ == "__main__": | |
image_folder = "images" # Replace with the path to your image folder | |
gif_name = "animated.gif" | |
create_gif(image_folder, gif_name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment