|
import argparse |
|
import glob |
|
import os |
|
from pathlib import Path |
|
from PIL import Image |
|
|
|
|
|
def main(): |
|
|
|
parser = argparse.ArgumentParser() |
|
parser.add_argument("directory", type=str, |
|
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("--quality", type=int, default=95, |
|
help="the JPEG quality (0-100)") |
|
parser.add_argument("--delete_originals", action="store_true", |
|
help="whether to delete the original files after conversion") |
|
|
|
|
|
args = parser.parse_args() |
|
directory = args.directory |
|
in_ext = args.in_ext |
|
out_ext = "jpg" |
|
quality = args.quality |
|
delete_originals = args.delete_originals |
|
|
|
|
|
file_pattern = f"*.{in_ext}" |
|
|
|
|
|
files = glob.glob(os.path.join(directory, file_pattern)) |
|
|
|
|
|
for file in files: |
|
|
|
img = Image.open(file) |
|
|
|
|
|
new_path = Path(file).with_suffix(f".{out_ext}") |
|
|
|
|
|
if new_path.exists(): |
|
|
|
print(f"Skipping {file} because {new_path} already exists") |
|
continue |
|
|
|
|
|
img.save(new_path, quality=quality, optimize=True) |
|
|
|
|
|
if delete_originals: |
|
os.remove(file) |
|
|
|
|
|
if __name__ == "__main__": |
|
main() |
|
|