photo-viewer-backend/scripts/resize-img

64 lines
1.5 KiB
Plaintext
Raw 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:
print("Error: You must specify an input file")
2023-11-13 02:03:04 +08:00
exit(1)
elif argn == 2:
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:
print(f"Error: 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/4, 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:
print(f"Error: Cannot save file {output_image_path}")
image.close()
2023-11-13 02:03:04 +08:00
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()