|
| 1 | +import sys |
| 2 | +import os |
| 3 | +from PIL import Image |
| 4 | + |
| 5 | +DPI = 72 |
| 6 | + |
| 7 | +def get_image_dimensions(image_path): |
| 8 | + """Gets image dimensions in pixels and points.""" |
| 9 | + try: |
| 10 | + image = Image.open(image_path) |
| 11 | + width, height = image.size |
| 12 | + dpi = image.info.get('dpi', (DPI, DPI)) |
| 13 | + print(f" Image dimensions: width={width}, height={height}, dpi={dpi}") |
| 14 | + return width, height, dpi |
| 15 | + except Exception as e: |
| 16 | + print(f"Error opening or processing image: {e}") |
| 17 | + sys.exit(1) |
| 18 | + |
| 19 | +file_path = sys.argv[1] |
| 20 | +print(f"Processing image: {file_path}.jpg") |
| 21 | + |
| 22 | +# Check if the file exists |
| 23 | +if not os.path.exists(f"{file_path}.jpg"): |
| 24 | + print(f"Error: File {file_path}.jpg not found.") |
| 25 | + sys.exit(1) |
| 26 | + |
| 27 | +# Get image dimensions using PIL |
| 28 | +width, height, dpi = get_image_dimensions(f"{file_path}.jpg") |
| 29 | + |
| 30 | +# Calculate scale factor based on desired height of 480, maintaining aspect ratio |
| 31 | +scale_factor = 480 / height |
| 32 | +print(f" Calculated scale factor: {scale_factor}") |
| 33 | + |
| 34 | +# Calculate new width based on scale factor |
| 35 | +new_width = int(width * scale_factor) |
| 36 | +print(f" New width: {new_width}") |
| 37 | + |
| 38 | +try: |
| 39 | + # Open the image |
| 40 | + image = Image.open(f"{file_path}.jpg") |
| 41 | + print(" Image opened successfully.") |
| 42 | + |
| 43 | + # Resize the image |
| 44 | + resized_image = image.resize((new_width, 480), Image.Resampling.LANCZOS) |
| 45 | + print(" Image resized successfully.") |
| 46 | + |
| 47 | + # Calculate the cropping box |
| 48 | + left = (resized_image.width - 854) / 2 |
| 49 | + top = 0 |
| 50 | + right = (resized_image.width + 854) / 2 |
| 51 | + bottom = 480 |
| 52 | + print(f" Cropping box: left={left}, top={top}, right={right}, bottom={bottom}") |
| 53 | + |
| 54 | + # Crop the image |
| 55 | + cropped_image = resized_image.crop((left, top, right, bottom)) |
| 56 | + print(" Image cropped successfully.") |
| 57 | + |
| 58 | + # Save the processed image, overwriting the original |
| 59 | + cropped_image.save(f"{file_path}.jpg") |
| 60 | + print(f" Image saved to {file_path}.jpg") |
| 61 | + |
| 62 | + |
| 63 | +except Exception as e: |
| 64 | + print(f"Error processing image: {e}") |
| 65 | + sys.exit(1) |
0 commit comments