""" Image processing utility functions """ from PIL import Image import os def remove_image_metadata(image_path: str) -> None: """ Remove metadata information from image file Args: image_path: Path to the image file """ if not os.path.exists(image_path): print(f"Warning: Image file does not exist: {image_path}") return try: # Load original image img = Image.open(image_path) # Create new image without metadata # Preserve image mode and size img_without_metadata = Image.new(img.mode, img.size) img_without_metadata.putdata(list(img.getdata())) # Save without any metadata img_without_metadata.save(image_path, format='PNG') print(f"Removed image metadata: {image_path}") except Exception as e: print(f"Failed to remove metadata ({image_path}): {str(e)}") def remove_multiple_images_metadata(image_paths: list) -> None: """ Batch remove metadata from multiple image files Args: image_paths: List of image file paths """ for path in image_paths: remove_image_metadata(path) def resize_and_optimize_image(image_path: str, target_long_edge: int = 1536) -> None: """ Resize image (long edge) and optimize PNG compression, while removing metadata Args: image_path: Path to the image file target_long_edge: Target long edge size, default 1536 (768×2) """ if not os.path.exists(image_path): print(f"Warning: Image file does not exist: {image_path}") return try: # Load original image img = Image.open(image_path) original_size = img.size # Calculate scaling ratio width, height = img.size long_edge = max(width, height) # If long edge is already smaller than target, only optimize compression if long_edge <= target_long_edge: print(f"Image size {original_size} is already smaller than target, only optimizing compression: {image_path}") img.save( image_path, format='PNG', compress_level=9, # Maximum compression level (0-9) optimize=True # Enable optimization ) return # Calculate new dimensions scale = target_long_edge / long_edge new_width = int(width * scale) new_height = int(height * scale) # Resize using high-quality Lanczos resampling algorithm img_resized = img.resize((new_width, new_height), Image.Resampling.LANCZOS) # Save optimized image (without metadata) img_resized.save( image_path, format='PNG', compress_level=9, # Maximum compression level optimize=True # Enable optimization ) print(f"Image resized and optimized: {image_path}") print(f" Original size: {original_size} -> New size: ({new_width}, {new_height})") # Display file size if os.path.exists(image_path): file_size_mb = os.path.getsize(image_path) / (1024 * 1024) print(f" File size: {file_size_mb:.2f} MB") except Exception as e: print(f"Failed to resize and optimize image ({image_path}): {str(e)}")