User blog:Toto89/GIFs

import glob

from PIL import Image

import numpy as np

import os

def add_margin(pil_img, top, left, size):

width, height = pil_img.size

result = Image.new(pil_img.mode, size, (255, 0, 0, 0))

result.paste(pil_img, (left, top))

return result


 * 1) Find the shadow's bottom right pixel

def get_shadow(pil_img):

shadow = (0, 0)

ni = np.array(pil_img)

alpha = ni[:,:,3]

for i in range(len(alpha)):

for j in range(len(alpha[i])):

if alpha[i][j] == 89:

shadow = (i, j)

return shadow

def make_gif(frame_folder, name):

images = [Image.open(image) for image in glob.glob(f"{frame_folder}/{name}*.PNG")]

### New size of the output ###

top_m, left_m, right_m, bottom_m = 0, 0, 0, 0

for image in images:

ni = np.array(image)

shadow = get_shadow(image)

top_m = max(top_m, shadow[0])

left_m =  max(left_m, shadow[1])

right_m = max(right_m, ni.shape[1]-shadow[1])

bottom_m = max(bottom_m, ni.shape[0]-shadow[0])

size = (right_m+left_m, top_m+bottom_m)

new_images = []

for image in images:

ni = np.array(image)

shadow = get_shadow(image)

bottom_margin =  0,ni.shape[0]-shadow[0]-bottom_m

new_image = add_margin(image, top_m-shadow[0], left_m-shadow[1], size)

new_image = new_image.resize(tuple(i * 4 for i in new_image.size), Image.NEAREST)

new_images.append(new_image)

new_images[0].save(path+"gif\\"+name+".gif", format="GIF", append_images=new_images,

save_all=True, duration=80, loop=0, disposal=2, transparency=0)

path = "C:\\Users\\"

files = os.listdir(path)

files_file = [f for f in files if os.path.isfile(os.path.join(path, f))]

sprite_names = list(set([f[:-12] for f in files_file]))

for s in sprite_names:

make_gif(path, s)