Last active
January 1, 2022 06:46
-
-
Save jonowo/42257e0d282c542c0aece409c5f03070 to your computer and use it in GitHub Desktop.
Resize an animated GIF to 512 x 512 by scaling and padding.
This file contains 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
""" | |
Resize an animated GIF to 512 x 512 by scaling the photo to fit | |
then padding the remaining space with the color of the topleft pixel. | |
Note: May not work well with GIFs with transparency. | |
To turn GIFs into animated stickers for Signal, resize them with this script before | |
converting them to APNG with the gif2apng CLI (http://gif2apng.sourceforge.net/). | |
""" | |
from PIL import Image, ImageOps, ImageSequence | |
def resize(from_path: str, to_path: str) -> None: | |
with Image.open(from_path) as gif: | |
frames = [] | |
size = gif.size | |
ratio = 512 / max(size) | |
for frame in ImageSequence.Iterator(gif): | |
c = frame.getpixel((0, 0)) # Topleft pixel as padding color | |
frame = frame.resize((round(size[0] * ratio), round(size[1] * ratio))) | |
dw = 512 - frame.size[0] | |
dh = 512 - frame.size[1] | |
padding = (dw // 2, dh // 2, dw - dw // 2, dh - dh // 2) | |
im = ImageOps.expand(frame, padding, fill=c) | |
im.info = frame.info | |
frames.append(im) | |
frames[0].save(to_path, save_all=True, append_images=frames[1:], disposal=2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment