File size: 1,791 Bytes
705282e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from PIL import Image
import os
from typing import Literal, Optional

def compress_image(
    input_path: str,
    output_path: str,
    quality: int = 85,
    format: Literal["JPEG", "PNG", "WEBP"] = "JPEG",
    max_width: Optional[int] = None,
    max_height: Optional[int] = None
) -> str:
    """
    Compress an image file.
    
    Args:
        input_path: Path to input image
        output_path: Path for compressed output
        quality: Compression quality 1-95 (for JPEG/WEBP)
        format: Output format
        max_width: Maximum width (optional)
        max_height: Maximum height (optional)
    """
    try:
        if not os.path.splitext(output_path)[1]:
            extension_map = {"JPEG": ".jpg", "PNG": ".png", "WEBP": ".webp"}
            output_path = output_path + extension_map[format]
        
        with Image.open(input_path) as img:
            if format == "JPEG" and img.mode in ("RGBA", "P"):
                img = img.convert("RGB")
            
            if max_width or max_height:
                img.thumbnail((max_width or img.width, max_height or img.height), Image.Resampling.LANCZOS)
            
            save_kwargs = {"format": format, "optimize": True}
            if format in ["JPEG", "WEBP"]:
                save_kwargs["quality"] = quality
            
            img.save(output_path, **save_kwargs)

        original_size = os.path.getsize(input_path) / 1024 / 1024  
        compressed_size = os.path.getsize(output_path) / 1024 / 1024 
        reduction = (1 - compressed_size/original_size) * 100
        
        return f"✅ Compressed successfully!\nOriginal: {original_size:.2f}MB → Compressed: {compressed_size:.2f}MB\nReduction: {reduction:.1f}%"
    
    except Exception as e:
        return f"❌ Error: {str(e)}"