Last active
February 6, 2019 03:52
-
-
Save timothycarambat/05c38b3c56e34e5d67a705e9689c1818 to your computer and use it in GitHub Desktop.
In an S3 bucket, take all gifs and overwrite them with a single frame of the same 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
import boto3 | |
import random | |
from PIL import Image | |
s3 = boto3.resource('s3') | |
bucket_name = "my-bucket" | |
bucket = s3.Bucket(bucket_name) | |
exception_file_name = "images/7df7a570-2348-11e9-8b57-e3db97667bbd.gif" | |
files_to_remove = [] | |
for key in bucket.objects.all(): | |
file_name = key.key | |
if file_name == exception_file_name: | |
continue | |
if "images/" in file_name and ".gif" in file_name: | |
files_to_remove.append(file_name) | |
print(f"{len(files_to_remove)} files to convert") | |
for file in files_to_remove: | |
print(f"Working on File {file}") | |
# get and save the gif locally | |
tmp_file = 'tmp_gif.gif' | |
tmp_single_gif = 'tmp_single.gif' | |
bucket.download_file(file, tmp_file) | |
#Open image and get single frame and upload back to s3 | |
with Image.open(tmp_file) as im: | |
num_frames = im.n_frames | |
if num_frames == 1: | |
print("Gif is already single Frame GIF") | |
continue | |
random_frame = random.randint(0,num_frames-1) | |
#get random frame | |
im.seek(random_frame) | |
im.save(tmp_single_gif) | |
bucket.upload_file(tmp_single_gif, file) | |
print(f"All Files Cleaned up in bucket {bucket_name}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment