Certainly! Below is a Python script that reads an image, scales it down to have approximately 1,048,576 pixels (which is 1024 x 1024), and adjusts the image dimensions so that both the width and height are the closest multiples of 64. It uses the Pillow library (a fork of PIL) for image processing.
Please make sure you have the Pillow library installed. You can install it using:
pip install Pillow
Here is the script:
from PIL import Image
import sys
import os
def resize_image(input_image_path, output_image_path, target_pixels=1048576, multiple=64):
"""
Resizes an image to have approximately the target number of pixels, with dimensions
adjusted to the closest multiples of a specified number (default is 64).
"""
# Open the image file
image = Image.open(input_image_path)
width_o, height_o = image.size
aspect_ratio = width_o / height_o
# Compute the target product of the scaled dimensions in terms of multiples
target_ij = target_pixels / (multiple ** 2)
target_ij = int(round(target_ij))
# Initialize variables to find the best dimensions
min_total_error = float('inf')
best_i = None
best_j = None
max_i = int((target_ij) ** 0.5) * 4 # Set an upper limit for i
for i in range(1, max_i):
# Calculate j based on the aspect ratio
j = int(round(i / aspect_ratio))
if j <= 0:
continue
total_pixels = i * j
pixel_error = abs(total_pixels - target_ij)
current_aspect_ratio = i / j
aspect_ratio_error = abs(current_aspect_ratio - aspect_ratio)
# Define the total error with weighted importance
total_error = pixel_error + (100 * aspect_ratio_error)
if total_error < min_total_error:
min_total_error = total_error
best_i = i
best_j = j
if best_i and best_j:
# Calculate the new dimensions
width_n = multiple * best_i
height_n = multiple * best_j
print(f"Original size: {width_o}x{height_o}")
print(f"Resized to: {width_n}x{height_n} (Width and Height are multiples of {multiple})")
# Resize the image
resized_image = image.resize((width_n, height_n), Image.LANCZOS)
resized_image.save(output_image_path)
print(f"Resized image saved to {output_image_path}")
else:
print("Could not find suitable dimensions.")
def main():
if len(sys.argv) < 2:
print("Usage: python resize_image.py input_image.jpg [output_image.jpg]")
sys.exit(1)
input_image_path = sys.argv[1]
if len(sys.argv) >= 3:
output_image_path = sys.argv[2]
else:
base, ext = os.path.splitext(input_image_path)
output_image_path = f"{base}_resized{ext}"
resize_image(input_image_path, output_image_path)
if __name__ == "__main__":
main()
Usage:
Save the script as resize_image.py and run it from the command line:
python resize_image.py input_image.jpg output_image.jpg
- Replace
input_image.jpg with the path to your input image.
- Replace
output_image.jpg with the desired path for the output image (optional). If you don't provide an output filename, it will save the resized image with _resized appended to the original filename.
Explanation:
- Aspect Ratio Preservation: The script calculates the aspect ratio of the original image to ensure that the resized image maintains the same proportions.
- Dimension Adjustment: It searches for the best width and height that are multiples of 64 and whose product is approximately the target number of pixels.
- Resizing: The image is resized using high-quality downsampling (
Image.LANCZOS filter).
Example:
python resize_image.py my_photo.jpg
This will create a resized image named my_photo_resized.jpg with dimensions adjusted to the closest multiples of 64 and approximately 1,048,576 pixels in total.
Feel free to adjust the target_pixels and multiple parameters in the resize_image function if you need different settings.
Let me know if you need any further assistance!