84 lines
2.5 KiB
Python
84 lines
2.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Convert PNG images to standard TGA RLE image files."""
|
|
|
|
import argparse
|
|
from pathlib import Path
|
|
|
|
|
|
def iter_inputs(input_path, recursive):
|
|
if input_path.is_file():
|
|
if input_path.suffix.lower() != ".png":
|
|
raise SystemExit(f"input file is not a PNG: {input_path}")
|
|
yield input_path
|
|
return
|
|
|
|
pattern = "**/*.png" if recursive else "*.png"
|
|
yield from sorted(input_path.glob(pattern))
|
|
|
|
|
|
def output_path_for(input_file, input_root, output):
|
|
if output is None:
|
|
return input_file.with_suffix(".rle")
|
|
|
|
if input_root.is_file():
|
|
return output
|
|
|
|
relative = input_file.relative_to(input_root)
|
|
return (output / relative).with_suffix(".rle")
|
|
|
|
|
|
def convert_file(input_file, input_root, output):
|
|
try:
|
|
from PIL import Image
|
|
except ImportError as exc:
|
|
raise SystemExit(
|
|
"Pillow is required. Install it with: python -m pip install Pillow"
|
|
) from exc
|
|
|
|
out_path = output_path_for(input_file, input_root, output)
|
|
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
with Image.open(input_file) as image:
|
|
converted = image.convert("RGBA")
|
|
width, height = converted.size
|
|
converted.save(out_path, format="TGA", compression="tga_rle")
|
|
print(f"{input_file} -> {out_path} ({width}x{height})")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(
|
|
description="Convert PNG files to standard TGA RLE files using Pillow.",
|
|
)
|
|
parser.add_argument("input", type=Path, help="PNG file or directory containing PNG files.")
|
|
parser.add_argument(
|
|
"-o",
|
|
"--output",
|
|
type=Path,
|
|
help="Output .rle file for one input file, or output directory for an input directory.",
|
|
)
|
|
parser.add_argument(
|
|
"-r",
|
|
"--recursive",
|
|
action="store_true",
|
|
help="Recursively convert PNG files when input is a directory.",
|
|
)
|
|
args = parser.parse_args()
|
|
|
|
input_path = args.input.resolve()
|
|
if not input_path.exists():
|
|
raise SystemExit(f"input path does not exist: {input_path}")
|
|
|
|
output = args.output.resolve() if args.output is not None else None
|
|
inputs = list(iter_inputs(input_path, args.recursive))
|
|
if not inputs:
|
|
raise SystemExit(f"no PNG files found in: {input_path}")
|
|
|
|
if input_path.is_file() and output is not None and output.suffix.lower() != ".rle":
|
|
raise SystemExit("single-file output must use a .rle suffix")
|
|
|
|
for input_file in inputs:
|
|
convert_file(input_file, input_path, output)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|