Skip to content

Instantly share code, notes, and snippets.

@iantbutler01
Created March 16, 2023 02:44
Show Gist options
  • Save iantbutler01/8c9bcda305cbaeadea5e188e5bb90e3b to your computer and use it in GitHub Desktop.
Save iantbutler01/8c9bcda305cbaeadea5e188e5bb90e3b to your computer and use it in GitHub Desktop.
Quick script to convert gifs to ascii animations.
import colorama
import time
from PIL import Image, ImageSequence
from list2term import Lines
import argparse
import traceback
import logging
import sys
import os
from ascii_magic import AsciiArt
class Animator():
def __init__(self, file, columns=150, loops=5):
if not os.path.isfile(file):
raise ValueError(f'The file "{file}" is not valid')
self.file = file
self.columns = columns
self.loops = loops
self.animation = []
def animate(self):
image = Image.open(self.file)
frame_iterator = ImageSequence.Iterator(image)
for frame in frame_iterator:
ascii_art = AsciiArt.from_pillow_image(frame)
_ascii = ascii_art.to_ascii(back=colorama.ansi.AnsiBack.BLACK).split("\n")
self.animation.append(_ascii)
for _ in range(0, self.loops):
with Lines(self.animation[0], max_chars=len(self.animation[0][0])) as lines:
for frame in self.animation:
for index, _ in enumerate(frame):
lines[index] = frame[index]
self._sleep()
def _sleep(self):
time.sleep(0.03)
def main():
parser = argparse.ArgumentParser(description='Ascii Art Animator from GIF')
parser.add_argument('-f', '--file', type=str, help='the path to a gif file')
parser.add_argument('-d', '--debug', action='store_true', help='display debug messages to stdout')
parser.add_argument('-m', '--max_loops', type=int, default=1, help='maximum number of loops, set to 0 to loop through image until keyboard interrupt (default 1)')
parser.add_argument('-c', '--columns', type=int, default=150, help='the number of characters per row (default 150)')
args = parser.parse_args()
if args.debug:
logging.basicConfig(level=logging.DEBUG)
try:
animator = Animator(
args.file,
loops=args.max_loops,
columns=args.columns
)
animator.animate()
except argparse.ArgumentError:
parser.print_help()
except Exception as exception:
sys.exit(2)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment