Last active
January 19, 2020 19:56
-
-
Save Mukundan314/0935c358646086762239b0b72495a802 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pathlib | |
import sys | |
import glob | |
import os | |
import io | |
from PIL import Image | |
def main(): | |
inp_directory = pathlib.Path(input("Input Directory: ")) | |
out_directory = inp_directory / 'resized' | |
out_directory.mkdir(exist_ok=True) | |
files = [f for f in inp_directory.glob('*') if f.is_file()] | |
for file in files: | |
image = Image.open(file).convert('RGB') | |
if image.width < image.height: | |
resized = image.resize((image.width * 400 // image.height, 400)) | |
else: | |
resized = image.resize((400, image.height * 400 // image.width)) | |
lo, hi = 1, 95 | |
while lo < hi: | |
mi = lo + (hi - lo) // 2 | |
f = io.BytesIO() | |
resized.save(f, format="jpeg", quality=mi) | |
if f.getbuffer().nbytes > 65536: | |
hi = mi | |
else: | |
lo = mi + 1 | |
with (out_directory / file.name).with_suffix('.jpeg').open('wb') as out_file: | |
out_file.write(f.getvalue()) | |
if __name__ == "__main__": | |
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import pathlib | |
import sys | |
import glob | |
import os | |
import io | |
from PIL import Image | |
def main(argv): | |
parser = argparse.ArgumentParser() | |
parser.add_argument('images_directory', type=pathlib.Path) | |
parser.add_argument('-s', '--max-size', type=int, default=65536) | |
args = parser.parse_args(argv[1:]) | |
out_directory = args.images_directory / 'resized' | |
out_directory.mkdir(exist_ok=True) | |
files = [f for f in args.images_directory.glob('*') if f.is_file()] | |
for file in files: | |
image = Image.open(file).convert('RGB') | |
if image.width < image.height: | |
resized = image.resize((image.width * 400 // image.height, 400)) | |
else: | |
resized = image.resize((400, image.height * 400 // image.width)) | |
lo, hi = 1, 95 | |
while lo < hi: | |
mi = lo + (hi - lo) // 2 | |
f = io.BytesIO() | |
resized.save(f, format="jpeg", quality=mi) | |
if f.getbuffer().nbytes > args.max_size: | |
hi = mi | |
else: | |
lo = mi + 1 | |
with (out_directory / file.name).with_suffix('.jpeg').open('wb') as out_file: | |
out_file.write(f.getvalue()) | |
if __name__ == "__main__": | |
main(sys.argv) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment