import argparse, pathlib, subprocess, sys from wand.image import Image supported_glob = "[jpJP][npNP][egEG]" def sanity_check_system(): r = subprocess.call("magick -version", shell=True) == 0 if not r: sys.exit("ImageMagick not installed. Aborting...") def parse_format(format_str): fmt = format_str.lower() if 'x' in fmt: w_h = fmt.split('x') w = int(w_h[0]) if w_h[0] != '' else 0 h = int(w_h[1]) if w_h[1] != '' else 0 return(w, h, fmt) return (None, None, None) def convert(filepath : pathlib.Path, fmt : tuple, output_dir: pathlib.Path): (w, h, f) = fmt # img exists? output = output_dir / filepath.name if output.exists() and output.is_file(): with Image(filename=str(output)) as img: if w > 0 and img.width == w or h > 0 and img.height == h: return output with Image(filename=str(filepath)) as img: print(f". converting {filepath}") print(f" > {img.size}") img.resolution = (72, 72) if w > 0 and img.width > w or h > 0 and img.height > h: img.transform(resize=f) print(f" > {img.size}") img.save(filename=str(output)) return output def convert_all(input_dir: pathlib.Path, fmt : tuple, output_dir: pathlib.Path): img_files = input_dir.glob("*." + supported_glob + "*") for i in img_files: convert(i, fmt, output_dir) if __name__ == '__main__': p = argparse.ArgumentParser(description='Converts images files to other formats (using wand/ImageMagick)'); p.add_argument('-i', '--input', help='input directory'); p.add_argument('-o', '--output', help='output directory'); p.add_argument('-f', '--format', help='output formats (ex. 1000x)'); sanity_check_system() args = p.parse_args() if not args.format: sys.exit("No formats specified. Aborting.") input_dir = pathlib.Path(".") if args.input: input_dir = pathlib.Path(args.input) if not input_dir.exists() or not input_dir.is_dir(): sys.exit(f"Input {str(input_dir)} is not a directory. Aborting.") output_dir = input_dir / "img-resize" if args.output: output_dir = pathlib.Path(args.output) output_dir.mkdir(parents=True, exist_ok=True) (w, h, fmt) = parse_format(args.format) if not fmt: sys.exit(f"Format {str(args.format)} is not valid. Aborting.") img_files = input_dir.glob("*." + supported_glob + "*") for i in img_files: convert(i, (w, h, fmt), output_dir)