pyanimate/pyanimate.py
2022-11-23 10:51:48 -08:00

127 lines
3.0 KiB
Python

import os
from PIL import Image
import tempfile
class Video(object):
def __init__(self, framerate, width, height):
self.framerate = framerate
self.width = width
self.height = height
self.sprites = []
def add_sprite(self, sprite):
self.sprites.append(sprite)
def render(self, outpath):
"""
render the video to a file
for frame in frames:
canvas = image()
for sprite in sprites:
sprite.next_frame()
sprite.draw(canvas)
canvas.save(...)
ffmepeg()
"""
with tempfile.TemporaryDirectory() as tmpdir:
for framenum in range(0, 30):
canvas = Image.new('RGB', (self.width, self.height, ))
for sprite in self.sprites:
sprite.draw(canvas)
with open(os.path.join(tmpdir, "frame_{:08d}.png".format(framenum)), "wb") as f:
canvas.save(f, "PNG")
for sprite in self.sprites:
sprite.next_frame()
print("done!")
os.system("open {}".format(tmpdir))
input()
class Source(object):
def __init__(self, file_path):
self.file_path = file_path
self.load()
def load(self):
"""
load the media from disk
"""
raise NotImplementedError()
class Sprite(object):
def __init__(self, source, position=(0, 0)):
self.source = source
self.position = position
self.visible = False
self.animations = []
def add_animation(self, animation):
self.animations.append(animation)
#TODO transforms that can modify the image e.g. scale it
# also, AddTransformAnimation/RemoveTransformAnimation to make modifications on the fly
# also, TweenTransformationAnimation
# def add_transform(self, transform):
# pass
def get_pending_animations(self):
return self.animations#TODO
def next_frame(self):
for animation in self.get_pending_animations():
animation.apply(self)
def draw(self, canvas):
"""
Draw the sprite on top of the given canvas
"""
raise NotImplementedError()
class ImageSprite(Sprite):
def __init__(self, source, position=(0, 0)):
super().__init__(source, position)
def draw(self, canvas):
"""
Draw the sprite on top of the given canvas
"""
# raise NotImplementedError("xd")
# pass
canvas.paste(self.source.img, (0, 0))
class Animation(object):
# def __init__(self, path=None, filters=None, transforms=None, after=None):
# pass
def apply(self, sprite):
raise NotImplementedError()
class ImageSource(Source):
def load(self):
self.img = Image.open(self.file_path)
class VideoSource(Source):
pass
class ShowAnimation(Animation):
def apply(self, sprite):
sprite.visible = True
class HideAnimation(Animation):
def apply(self, sprite):
sprite.visible = False