63 lines
1.4 KiB
Plaintext
63 lines
1.4 KiB
Plaintext
|
#!/usr/bin/python
|
||
|
from PIL import Image
|
||
|
import sys
|
||
|
|
||
|
|
||
|
def main():
|
||
|
target_width = 2048
|
||
|
|
||
|
argn = len(sys.argv)
|
||
|
|
||
|
if argn == 1:
|
||
|
print("You must specify an input file")
|
||
|
exit(1)
|
||
|
elif argn == 2:
|
||
|
print("You must specify an output file")
|
||
|
exit(1)
|
||
|
|
||
|
input_image_path = sys.argv[1]
|
||
|
output_image_path = sys.argv[2]
|
||
|
|
||
|
try:
|
||
|
image = Image.open(input_image_path)
|
||
|
except IOError:
|
||
|
print(f"Cannot open image file {input_image_path}")
|
||
|
exit(1)
|
||
|
|
||
|
width, height = image.size
|
||
|
new_height = int(target_width * height / width)
|
||
|
|
||
|
image = image.resize((target_width, new_height), Image.Resampling.BICUBIC)
|
||
|
image = rotate_image(image)
|
||
|
|
||
|
kwargs = {"quality": 50}
|
||
|
if "exif" in image.info.keys():
|
||
|
kwargs["exif"] = image.info["exif"]
|
||
|
|
||
|
try:
|
||
|
image.save(output_image_path, **kwargs)
|
||
|
except IOError:
|
||
|
print(f"Cannot save file {output_image_path}")
|
||
|
exit(1)
|
||
|
|
||
|
|
||
|
def rotate_image(image):
|
||
|
exif = image.getexif()
|
||
|
if exif is None:
|
||
|
return image
|
||
|
|
||
|
orientation = exif.get(0x0012, 1) # 0x0112 is the EXIF code for orientation
|
||
|
if orientation == 1:
|
||
|
return image
|
||
|
elif orientation == 3:
|
||
|
image = image.rotate(180, expand=True)
|
||
|
elif orientation == 6:
|
||
|
image = image.rotate(270, expand=True)
|
||
|
elif orientation == 8:
|
||
|
image = image.rotate(90, expand=True)
|
||
|
return image
|
||
|
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
main()
|