Skip to content

Instantly share code, notes, and snippets.

@coolreader18
Last active February 12, 2021 14:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coolreader18/3540282c3283bc4583621e13872a1d9d to your computer and use it in GitHub Desktop.
Save coolreader18/3540282c3283bc4583621e13872a1d9d to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import PIL.Image
from PIL import ImageSequence
import wand.image
from io import BytesIO, RawIOBase
def gmagik(gif: PIL.Image.Image, out: RawIOBase):
total = gif.n_frames
out_frames = []
for idx, frame in enumerate(ImageSequence.Iterator(gif), start=1):
print(f"Processing frame {idx}/{total}")
b = BytesIO()
magik(frame, b)
out_frames.append(PIL.Image.open(b))
print(f"Done processing {total} frames")
out_frames[0].save(out, "GIF", loop=0, save_all=True, append_images=out_frames[1:])
out.seek(0)
def magik(im: PIL.Image.Image, out: RawIOBase):
b = BytesIO()
im.save(b, "gif")
b.seek(0)
im = wand.image.Image(file=b)
im.transform(resize="800x800>")
im.liquid_rescale(
width=int(im.width * 0.5), height=int(im.height * 0.5), delta_x=1, rigidity=0
)
im.liquid_rescale(
width=int(im.width * 1.5), height=int(im.height * 1.5), delta_x=2, rigidity=0
)
im.resize(im.width, im.height)
im.save(file=out)
out.seek(0)
if __name__ == "__main__":
import argparse, sys
parser = argparse.ArgumentParser("gmagik")
subparsers = parser.add_subparsers(required=True)
for action in ('magik', 'gmagik'):
action_parser = subparsers.add_parser(action)
action_parser.add_argument("input", nargs=1)
action_parser.add_argument("output", nargs=1)
action_parser.set_defaults(func=globals()[action])
args = parser.parse_args()
inp = args.input[0]
out = args.output[0]
try:
inp = PIL.Image.open(inp).copy()
with open(out, "wb") as f:
args.func(inp, f)
except Exception as e:
print("an exception occurred:", file=sys.stderr)
raise
@coolreader18
Copy link
Author

You need Pillow and Wand/ImageMagick installed, with Liquid Rescale enabled for ImageMagick (you have to recompile ImageMagick to get it, if it's not there already). Then, you can run:

$ ./gmagik.py gmagik input.gif gmagicked-output.gif
# or for magik on a single-frame image
$ ./gmagik.py magik input.png gmagicked-output.gif

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment