photo-viewer-backend/scripts/resize-img

67 lines
1.6 KiB
Plaintext
Raw Permalink Normal View History

2023-11-13 02:03:04 +08:00
#!/usr/bin/python
from PIL import Image
import sys
def main():
argn = len(sys.argv)
if argn == 1:
2023-11-18 16:41:32 +08:00
print_error("You must specify an input file")
2023-11-13 02:03:04 +08:00
exit(1)
elif argn == 2:
2023-11-18 16:41:32 +08:00
print_error("You must specify an output file")
2023-11-13 02:03:04 +08:00
exit(1)
input_image_path = sys.argv[1]
output_image_path = sys.argv[2]
try:
image = Image.open(input_image_path)
except IOError:
2023-11-18 16:41:32 +08:00
print_error(f"Cannot open image file {input_image_path}")
image.close()
2023-11-13 02:03:04 +08:00
exit(1)
width, height = image.size
target_width = int(max(width/2, 1280))
2023-11-13 02:03:04 +08:00
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:
2023-11-18 16:41:32 +08:00
print_error(f"Cannot save file {output_image_path}")
image.close()
2023-11-13 02:03:04 +08:00
exit(1)
2023-11-18 16:41:32 +08:00
def print_error(string):
print(f"resize-img Error: {string}")
2023-11-13 02:03:04 +08:00
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()