Sort wallpapers by resolution

This commit is contained in:
jpk 2022-05-30 09:12:38 +02:00
parent 6e2719f053
commit 6e84ac2b6e
2 changed files with 36 additions and 14 deletions

View File

@ -2,17 +2,32 @@ from pathlib import Path
import click import click
from .wallpapers import scan_directory from .wallpapers import move_wallpaper, scan_directory
@click.command() @click.command()
@click.argument( @click.argument(
"directory", type=click.Path(exists=True, file_okay=False, dir_okay=True) "source",
type=click.Path(exists=True, file_okay=False, dir_okay=True),
default=Path("~/Pictures/wallpapers").expanduser(),
) )
def sort(directory): @click.argument(
for image in scan_directory(Path(directory).expanduser()): "target",
click.echo(image) type=click.Path(exists=False, file_okay=False, dir_okay=True),
default=Path("~/Pictures/wallpapers/by-resolution").expanduser(),
)
def sort(source: Path, target: Path):
if not target.exists():
target.mkdir()
for wallpaper in scan_directory(source):
filename, (xres, yres) = wallpaper
if filename.is_relative_to(target):
continue
new_filename = move_wallpaper(
filename, target / f"{xres}x{yres}/{filename.name}"
)
click.echo(new_filename)
if __name__ == "__main__": if __name__ == "__main__":
sort(None) sort(None, None)

View File

@ -1,12 +1,19 @@
import pathlib import os
from typing import Iterable from pathlib import Path
from typing import Iterable, Tuple
from PIL import Image from PIL import Image
def scan_directory(directory: pathlib.Path) -> Iterable[pathlib.Path]: def scan_directory(directory: Path) -> Iterable[Tuple[Path, Tuple[int, int]]]:
for filename in directory.iterdir(): for root, _, filenames in os.walk(directory):
if filename.is_file(): for filename in [Path(os.path.join(root, fname)) for fname in filenames]:
image = Image.open(filename) if filename.is_file():
print(image.size) image = Image.open(filename)
yield filename yield (filename, image.size)
def move_wallpaper(wallpaper: Path, target: Path) -> Path:
if not target.parent.exists():
target.parent.mkdir()
return wallpaper.rename(target)