|
import argparse
|
|
from pathlib import Path
|
|
import os
|
|
from PIL import Image
|
|
|
|
def writable_dir(target_path):
|
|
""" Check if a path is a valid directory and that it can be written to. """
|
|
path = Path(target_path)
|
|
if path.is_dir():
|
|
if os.access(path, os.W_OK):
|
|
return path
|
|
else:
|
|
raise argparse.ArgumentTypeError(f"Directory '{path}' is not writable.")
|
|
else:
|
|
raise argparse.ArgumentTypeError(f"Directory '{path}' does not exist.")
|
|
|
|
def main():
|
|
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("directory", type=writable_dir,
|
|
help="the directory containing the images to be converted")
|
|
parser.add_argument("--in_ext", type=str, default="webp",
|
|
help="the input file extension")
|
|
parser.add_argument("--out_ext", type=str, default="webp",
|
|
help="the output file extension")
|
|
parser.add_argument("--delete_originals", action="store_true",
|
|
help="whether to delete the original files after conversion")
|
|
|
|
|
|
args = parser.parse_args()
|
|
directory = Path(args.directory)
|
|
in_ext = args.in_ext
|
|
delete_originals = args.delete_originals
|
|
|
|
|
|
file_pattern = f"*.{in_ext}"
|
|
|
|
|
|
files = list(directory.glob(file_pattern))
|
|
|
|
|
|
for file in files:
|
|
try:
|
|
|
|
img = Image.open(file)
|
|
|
|
|
|
new_path = file.with_suffix(f".{args.out_ext}")
|
|
print(new_path)
|
|
|
|
|
|
if new_path.exists():
|
|
|
|
print(f"Skipping {file} because {new_path} already exists")
|
|
continue
|
|
|
|
|
|
img.save(new_path, lossless=True)
|
|
|
|
|
|
img.close()
|
|
|
|
|
|
if delete_originals:
|
|
file.unlink()
|
|
except Exception as e:
|
|
print(f"Error processing {file}: {e}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|
|
|