Skip to content

Instantly share code, notes, and snippets.

@andy0130tw
Created January 31, 2016 20:08
Show Gist options
  • Save andy0130tw/8a5c4ea27808fd28b8e2 to your computer and use it in GitHub Desktop.
Save andy0130tw/8a5c4ea27808fd28b8e2 to your computer and use it in GitHub Desktop.
Convert Facebook-downloaded stickers to GIF animations! You need Pillow and an image2gif script to use this. (The latter can be found in my Gist.)
#!/usr/bin/env python3
from os import path, makedirs
from PIL import Image
import image2gif
def splitImage_2x2(image):
w, h = image.size
assert((w % 2, h % 2) == (0, 0))
w1, h1 = w // 2, h // 2
crop_spec = [
(0 , 0 , w1 , h1), (w1 , 0 , w , h1),
(0 , h1 , w1 , h ), (w1 , h1 , w , h )
]
return [ image.crop(tup) for tup in crop_spec ]
def splitImage_3x3(image, cells):
w, h = image.size
assert((w % 3, h % 3) == (0, 0))
w1, h1 = w // 3, h // 3
w2, h2 = w1 * 2, h1 * 2
crop_spec = [
(0 , 0 , w1 , h1), (w1 , 0 , w2 , h1), (w2 , 0 , w , h1),
(0 , h1 , w1 , h2), (w1 , h1 , w2 , h2), (w2 , h1 , w , h2),
(0 , h2 , w1 , h ), (w1 , h2 , w2 , h ), (w2 , h2 , w , h )
]
return [ image.crop(tup) for i, tup in enumerate(crop_spec) if i < cells ]
def convert(fin, fout, frames):
print("Processing {}...".format(fin))
img = Image.open(fin).convert("RGBA")
assert(frames >= 4 and frames <= 9)
if frames == 4:
imageArr = splitImage_2x2(img)
elif frames > 4:
imageArr = splitImage_3x3(img, frames)
# XXX: subRectangles option results in wrong position somehow but it should be turned on...
image2gif.writeGif(path.join(fout, fin), imageArr, duration=0.139, dispose=2, subRectangles=False)
if __name__ == "__main__":
# src_2x = "orig/"
src_2x = "gif/"
src_3x = "gif_3x/"
distDir = "export/"
makedirs(path.join(distDir, src_2x), exist_ok=True)
makedirs(path.join(distDir, src_3x), exist_ok=True)
# convert(path.join(src_2x, "851591_279586302215635_1194745542_n.png"), distDir, 4)
convert(path.join(src_2x, "1.gif"), distDir, 4)
for i in range(1, 40):
convert(path.join(src_2x, "{}.gif".format(i)), distDir, 4)
convert(path.join(src_3x, "40.gif"), distDir, 8)
convert(path.join(src_3x, "41.gif"), distDir, 7)
convert(path.join(src_3x, "42.gif"), distDir, 8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment