from PIL import Image, ImageOps def resize_image_canvas(input_path, output_path, canvas_width, canvas_height, bg_color=(255, 255, 255)): """ Resizes an image to fit within a specific canvas size, centering it and adding padding. """ try: original_image = Image.open(input_path) # Calculate aspect ratios img_ratio = original_image.width / original_image.height canvas_ratio = canvas_width / canvas_height # Determine new dimensions if img_ratio > canvas_ratio: # Image is wider than canvas new_width = canvas_width new_height = int(canvas_width / img_ratio) else: # Image is taller than canvas new_height = canvas_height new_width = int(canvas_height * img_ratio) # Resize the original image resized_image = original_image.resize((new_width, new_height), Image.Resampling.LANCZOS) # Create a new canvas with the specified background color new_image = Image.new("RGB", (canvas_width, canvas_height), bg_color) # Calculate position to center the image x_offset = (canvas_width - new_width) // 2 y_offset = (canvas_height - new_height) // 2 # Paste the resized image onto the canvas new_image.paste(resized_image, (x_offset, y_offset)) # Save the result new_image.save(output_path, quality=95) print(f"Success! Image saved to {output_path}") except Exception as e: print(f"Error: {e}") if __name__ == "__main__": # Example usage: # Replace 'screenshot.png' with your actual file name # We will look for png or jpg files in current dir if not specified import glob import sys files = glob.glob("*.png") + glob.glob("*.jpg") + glob.glob("*.jpeg") if not files: print("No image files found in the current directory.") sys.exit(1) print("Found images:", files) input_file = files[0] # Take the first one found print(f"Processing {input_file}...") resize_image_canvas(input_file, "cws_screenshot_1280x800.png", 1280, 800, bg_color=(245, 247, 250)) # Light gray-ish background matching the app