61 lines
1.8 KiB
Python
61 lines
1.8 KiB
Python
"""Build an opaque, desktop-sized WebP exploration background."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
from pathlib import Path
|
|
|
|
from PIL import Image, ImageOps
|
|
|
|
|
|
def parse_args() -> argparse.Namespace:
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--input", required=True, type=Path)
|
|
parser.add_argument("--output", required=True, type=Path)
|
|
parser.add_argument("--width", type=int, default=1920)
|
|
parser.add_argument("--height", type=int, default=1080)
|
|
parser.add_argument("--quality", type=int, default=88)
|
|
return parser.parse_args()
|
|
|
|
|
|
def main() -> None:
|
|
args = parse_args()
|
|
if args.width <= 0 or args.height <= 0:
|
|
raise ValueError("Output dimensions must be positive.")
|
|
if not 1 <= args.quality <= 100:
|
|
raise ValueError("WebP quality must be between 1 and 100.")
|
|
|
|
output_path = args.output.resolve()
|
|
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
with Image.open(args.input) as source:
|
|
rgb_source = ImageOps.exif_transpose(source).convert("RGB")
|
|
resized = ImageOps.fit(
|
|
rgb_source,
|
|
(args.width, args.height),
|
|
method=Image.Resampling.LANCZOS,
|
|
centering=(0.5, 0.5),
|
|
)
|
|
resized.save(
|
|
output_path,
|
|
format="WEBP",
|
|
quality=args.quality,
|
|
method=6,
|
|
exact=False,
|
|
)
|
|
|
|
with Image.open(output_path) as result:
|
|
if result.size != (args.width, args.height) or result.mode != "RGB":
|
|
raise RuntimeError(
|
|
f"Unexpected output: {result.size[0]}x{result.size[1]} {result.mode}"
|
|
)
|
|
|
|
print(
|
|
f"Built {output_path} ({args.width}x{args.height}, "
|
|
f"{output_path.stat().st_size} bytes)."
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|