Files
rename_and_comprress_phone_…/compress_photos.py
2026-01-30 23:11:31 +03:30

261 lines
8.7 KiB
Python

#!/usr/bin/env python3
"""
Create compressed versions of photos with reduced file size.
Skips videos and only processes JPG, JPEG, and HEIC files.
"""
import sys
import subprocess
import shutil
from pathlib import Path
from PIL import Image
import pillow_heif
# Register HEIF opener with Pillow
pillow_heif.register_heif_opener()
def compress_heic(photo_path, output_dir, max_dimension=1920, quality=85):
"""
Compress HEIC file while preserving format and color space.
Uses macOS sips command.
Args:
photo_path: Path to the original HEIC photo
output_dir: Directory to save compressed photo
max_dimension: Maximum width or height (preserves aspect ratio)
quality: Quality level (1-100, higher is better)
Returns:
True if successful, False otherwise
"""
try:
# Check if sips is available (macOS)
if not shutil.which("sips"):
print(" Warning: sips not found, falling back to JPEG conversion")
return False
# Get original dimensions
with Image.open(photo_path) as img:
orig_width, orig_height = img.size
# Create output path with .heic extension
output_path = output_dir / (photo_path.stem + ".heic")
# Copy file first
shutil.copy2(photo_path, output_path)
# Resize if needed
if orig_width > max_dimension or orig_height > max_dimension:
if orig_width > orig_height:
new_width = max_dimension
new_height = int((max_dimension / orig_width) * orig_height)
else:
new_height = max_dimension
new_width = int((max_dimension / orig_height) * orig_width)
# Resize using sips
subprocess.run(
["sips", "-Z", str(max(new_width, new_height)), str(output_path)],
check=True,
capture_output=True,
)
else:
new_width, new_height = orig_width, orig_height
# Get file sizes
orig_size = photo_path.stat().st_size
new_size = output_path.stat().st_size
reduction = (1 - new_size / orig_size) * 100
print(f" ✓ {orig_width}x{orig_height} → {new_width}x{new_height}")
print(
f" {orig_size/1024/1024:.2f}MB → {new_size/1024/1024:.2f}MB ({reduction:.1f}% reduction)\n"
)
return True
except Exception as e:
print(f" Error compressing HEIC: {e}")
# Clean up failed output
if output_path.exists():
output_path.unlink()
return False
def compress_photo(photo_path, output_dir, max_dimension=1920, quality=85):
"""
Create a compressed version of a photo.
Args:
photo_path: Path to the original photo
output_dir: Directory to save compressed photo
max_dimension: Maximum width or height (preserves aspect ratio). Ignored if quality=100
quality: JPEG quality (1-100, higher is better). 100 = preserve original format
Returns:
True if successful, False otherwise
"""
try:
with Image.open(photo_path) as img:
# Get original dimensions
orig_width, orig_height = img.size
# Get ICC profile without converting color space
icc_profile = img.info.get("icc_profile")
# Convert to RGB for JPEG (without color space conversion)
if img.mode in ("RGBA", "P", "LA"):
img = img.convert("RGB")
elif img.mode != "RGB":
img = img.convert("RGB")
# Calculate new dimensions while preserving aspect ratio
if quality < 100 and (
orig_width > max_dimension or orig_height > max_dimension
):
if orig_width > orig_height:
new_width = max_dimension
new_height = int((max_dimension / orig_width) * orig_height)
else:
new_height = max_dimension
new_width = int((max_dimension / orig_height) * orig_width)
img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
else:
new_width, new_height = orig_width, orig_height
# Create output filename (always save as .jpg)
output_path = output_dir / (photo_path.stem + ".jpg")
# Save with compression, preserving ICC profile for accurate color display
save_kwargs = {
"quality": quality,
"optimize": True,
"subsampling": (
0 if quality >= 95 else 2
), # No chroma subsampling for high quality
}
if icc_profile:
save_kwargs["icc_profile"] = icc_profile
img.save(output_path, "JPEG", **save_kwargs)
# Get file sizes
orig_size = photo_path.stat().st_size
new_size = output_path.stat().st_size
reduction = (1 - new_size / orig_size) * 100
print(f" ✓ {orig_width}x{orig_height} → {new_width}x{new_height}")
print(
f" {orig_size/1024/1024:.2f}MB → {new_size/1024/1024:.2f}MB ({reduction:.1f}% reduction)\n"
)
return True
except Exception as e:
print(f" Error compressing: {e}\n")
return False
def compress_photos(root_directory, output_directory, max_dimension=1920, quality=85):
"""
Compress all photos in directory and subdirectories.
Args:
root_directory: Root directory to search for photos
output_directory: Directory to save compressed photos (maintains structure)
max_dimension: Maximum width or height for resized images
quality: JPEG quality (1-100)
"""
root_path = Path(root_directory)
output_path = Path(output_directory)
if not root_path.exists():
print(f"Error: Directory '{root_directory}' does not exist")
return
# Create output directory
output_path.mkdir(parents=True, exist_ok=True)
# Find all photo files (skip videos)
photo_extensions = {".jpg", ".jpeg", ".heic"}
photo_files = []
for ext in photo_extensions:
photo_files.extend(root_path.rglob(f"*{ext}"))
photo_files.extend(root_path.rglob(f"*{ext.upper()}"))
# Filter out macOS resource fork files
photo_files = [f for f in photo_files if not f.name.startswith("._")]
if not photo_files:
print("No photos found with JPG, JPEG, or HEIC extensions")
return
print(f"Found {len(photo_files)} photo(s)")
print(f"Settings: max dimension={max_dimension}px, quality={quality}\n")
success_count = 0
skip_count = 0
for photo_path in sorted(photo_files):
print(f"Processing: {photo_path.name}")
# Maintain directory structure in output
relative_path = photo_path.parent.relative_to(root_path)
photo_output_dir = output_path / relative_path
photo_output_dir.mkdir(parents=True, exist_ok=True)
# Always output as JPEG for compatibility
output_file = photo_output_dir / (photo_path.stem + ".jpg")
if output_file.exists():
print(f" Skipped: Already exists in output directory\n")
skip_count += 1
continue
# Convert to JPEG
success = compress_photo(photo_path, photo_output_dir, max_dimension, quality)
if success:
success_count += 1
else:
skip_count += 1
print(f"\nSummary:")
print(f" Compressed: {success_count}")
print(f" Skipped: {skip_count}")
print(f" Total: {len(photo_files)}")
def main():
if len(sys.argv) < 3:
print(
"Usage: python compress_photos.py <input_directory> <output_directory> [max_dimension] [quality]"
)
print("\nArguments:")
print(" input_directory Directory containing photos to compress")
print(" output_directory Directory to save compressed photos")
print(" max_dimension Maximum width/height in pixels (default: 1920)")
print(" quality JPEG quality 1-100 (default: 85)")
print("\nExamples:")
print(' python compress_photos.py "Photos" "Photos_Compressed"')
print(' python compress_photos.py "Photos" "Photos_Compressed" 1280 80')
sys.exit(1)
input_dir = sys.argv[1]
output_dir = sys.argv[2]
max_dimension = int(sys.argv[3]) if len(sys.argv) > 3 else 1920
quality = int(sys.argv[4]) if len(sys.argv) > 4 else 85
# Validate quality
if quality < 1 or quality > 100:
print("Error: Quality must be between 1 and 100")
sys.exit(1)
compress_photos(input_dir, output_dir, max_dimension, quality)
if __name__ == "__main__":
main()