Skip to content

Commit

Permalink
improved frame resizing for gallery animated preview
Browse files Browse the repository at this point in the history
  • Loading branch information
Barakudum committed Mar 5, 2024
1 parent b7a5474 commit caca752
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
15 changes: 11 additions & 4 deletions src/jarklin/cache/gallery.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,20 @@ def generate_image_preview(self) -> None:
shutil.copyfile(first_preview, self.dest.joinpath("preview.webp"))

def generate_animated_preview(self) -> None:
images = sorted(self.previews_dir.glob("*.webp"), key=lambda f: int(f.stem))[:self.max_images]
if not images:
import statistics

filepaths = sorted(self.previews_dir.glob("*.webp"), key=lambda f: int(f.stem))[:self.max_images]
if not filepaths:
raise FileExistsError("no previews found")

with ExitStack() as stack:
first, *frames = (stack.enter_context(Image.open(fp)) for fp in images)
images: t.List[Image.Image] = [stack.enter_context(Image.open(fp)) for fp in filepaths]
avg_width = round(statistics.mean((img.width for img in images)))
avg_height = round(statistics.mean((img.height for img in images)))

first, *frames = images
# this step is done to ensure all images have the same dimensions. otherwise the save will fail
frames = [stack.enter_context(frame.resize(first.size)) for frame in frames]
frames = [stack.enter_context(frame.resize((avg_width, avg_height))) for frame in frames]
# minimize_size=True => warned as slow
# method=6 => bit slower but better results
first.save(self.dest.joinpath("animated.webp"), format="WEBP", save_all=True, minimize_size=False,
Expand Down
5 changes: 3 additions & 2 deletions src/jarklin/cache/video.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,10 @@ def generate_image_preview(self) -> None:
shutil.copyfile(preview_source, self.dest.joinpath("preview.webp"))

def generate_animated_preview(self) -> None:
images = sorted(self.previews_cache.glob("*.png"), key=lambda f: int(f.stem))
filepaths = sorted(self.previews_cache.glob("*.png"), key=lambda f: int(f.stem))
with ExitStack() as stack:
first, *frames = (stack.enter_context(Image.open(fp)) for fp in images)
images: t.List[Image.Image] = [stack.enter_context(Image.open(fp)) for fp in filepaths]
first, *frames = images
first.save(self.dest.joinpath("animated.webp"), format="WEBP", save_all=True, minimize_size=False,
append_images=frames, duration=round(1000 / self.scene_fps), loop=0, method=6, quality=80)

Expand Down

0 comments on commit caca752

Please sign in to comment.