Exemples de Traitement d'Images Web Python

Exemples de traitement d'images Web Python utilisant PIL/Pillow incluant la lecture, l'enregistrement, le redimensionnement et la conversion de format

💻 Lire et Enregistrer une Image python

🟢 simple ⭐⭐

Lire et enregistrer des fichiers d'image dans divers formats (JPG, PNG, GIF, BMP) avec PIL/Pillow et obtenir des métadonnées d'image

⏱️ 20 min 🏷️ python, web, image, processing
Prerequisites: Basic Python, PIL/Pillow library
# Web Python Image Read & Save Examples
# Reading, saving, and getting image information using PIL/Pillow

# 1. Basic Image Operations
from PIL import Image
from typing import Optional, Tuple, List
import os

def open_image(filepath: str) -> Optional[Image.Image]:
    """
    Open image file

    Args:
        filepath: Path to image file

    Returns:
        PIL Image object or None if error
    """
    try:
        return Image.open(filepath)
    except FileNotFoundError:
        return None
    except Exception as e:
        print(f"Error opening image: {e}")
        return None

def save_image(image: Image.Image, filepath: str, format: Optional[str] = None, **kwargs) -> bool:
    """
    Save image to file

    Args:
        image: PIL Image object
        filepath: Output file path
        format: Image format (auto-detected from extension if None)
        **kwargs: Additional save parameters (quality, optimize, etc.)

    Returns:
        True if successful
    """
    try:
        # Create directory if not exists
        os.makedirs(os.path.dirname(filepath) or '.', exist_ok=True)
        image.save(filepath, format=format, **kwargs)
        return True
    except Exception as e:
        print(f"Error saving image: {e}")
        return False

def save_as_jpg(image: Image.Image, filepath: str, quality: int = 95) -> bool:
    """
    Save as JPEG format

    Args:
        image: PIL Image object
        filepath: Output file path
        quality: JPEG quality (1-100)

    Returns:
        True if successful
    """
    return save_image(image, filepath, quality=quality)

def save_as_png(image: Image.Image, filepath: str, optimize: bool = True) -> bool:
    """
    Save as PNG format

    Args:
        image: PIL Image object
        filepath: Output file path
        optimize: Enable PNG optimization

    Returns:
        True if successful
    """
    return save_image(image, filepath, optimize=optimize)

def save_as_gif(image: Image.Image, filepath: str) -> bool:
    """
    Save as GIF format

    Args:
        image: PIL Image object
        filepath: Output file path

    Returns:
        True if successful
    """
    return save_image(image, filepath)

def save_as_bmp(image: Image.Image, filepath: str) -> bool:
    """
    Save as BMP format

    Args:
        image: PIL Image object
        filepath: Output file path

    Returns:
        True if successful
    """
    return save_image(image, filepath)

# 2. Image Information
def get_image_size(image: Image.Image) -> Tuple[int, int]:
    """
    Get image dimensions

    Args:
        image: PIL Image object

    Returns:
        (width, height) tuple
    """
    return image.size

def get_image_width(image: Image.Image) -> int:
    """Get image width"""
    return image.width

def get_image_height(image: Image.Image) -> int:
    """Get image height"""
    return image.height

def get_image_format(image: Image.Image) -> Optional[str]:
    """Get image format (JPEG, PNG, etc.)"""
    return image.format

def get_image_mode(image: Image.Image) -> str:
    """
    Get image mode (RGB, RGBA, L, CMYK, etc.)

    Returns:
        Mode string
    """
    return image.mode

def get_image_info(image: Image.Image) -> dict:
    """
    Get comprehensive image information

    Args:
        image: PIL Image object

    Returns:
        Dictionary with image metadata
    """
    return {
        'format': image.format,
        'mode': image.mode,
        'size': image.size,
        'width': image.width,
        'height': image.height,
        'has_transparency': image.mode in ('RGBA', 'LA', 'PA') or 'transparency' in image.info
    }

def print_image_info(image: Image.Image) -> None:
    """Print image information"""
    info = get_image_info(image)
    print("Image Information:")
    for key, value in info.items():
        print(f"  {key}: {value}")

# 3. Image Mode Conversion
def convert_to_rgb(image: Image.Image) -> Image.Image:
    """
    Convert image to RGB mode

    Args:
        image: PIL Image object

    Returns:
        RGB Image
    """
    return image.convert('RGB')

def convert_to_rgba(image: Image.Image) -> Image.Image:
    """
    Convert image to RGBA mode

    Args:
        image: PIL Image object

    Returns:
        RGBA Image
    """
    return image.convert('RGBA')

def convert_to_grayscale(image: Image.Image) -> Image.Image:
    """
    Convert image to grayscale

    Args:
        image: PIL Image object

    Returns:
        Grayscale Image
    """
    return image.convert('L')

def convert_mode(image: Image.Image, mode: str) -> Image.Image:
    """
    Convert image to specified mode

    Args:
        image: PIL Image object
        mode: Target mode ('RGB', 'RGBA', 'L', 'CMYK', etc.)

    Returns:
        Converted Image
    """
    return image.convert(mode)

# 4. Batch Processing
def batch_convert_format(input_files: List[str], output_dir: str, output_format: str) -> List[str]:
    """
    Convert multiple images to specified format

    Args:
        input_files: List of input file paths
        output_dir: Output directory
        output_format: Target format ('jpg', 'png', etc.)

    Returns:
        List of output file paths
    """
    os.makedirs(output_dir, exist_ok=True)
    output_files = []

    for filepath in input_files:
        try:
            image = open_image(filepath)
            if image:
                basename = os.path.splitext(os.path.basename(filepath))[0]
                output_path = os.path.join(output_dir, f"{basename}.{output_format}")
                save_image(image, output_path)
                output_files.append(output_path)
        except Exception as e:
            print(f"Error processing {filepath}: {e}")

    return output_files

def batch_resize_save(input_files: List[str], output_dir: str, size: Tuple[int, int]) -> List[str]:
    """
    Resize multiple images and save

    Args:
        input_files: List of input file paths
        output_dir: Output directory
        size: Target size (width, height)

    Returns:
        List of output file paths
    """
    from PIL import Image
    os.makedirs(output_dir, exist_ok=True)
    output_files = []

    for filepath in input_files:
        try:
            image = open_image(filepath)
            if image:
                resized = image.resize(size)
                basename = os.path.basename(filepath)
                output_path = os.path.join(output_dir, basename)
                save_image(resized, output_path)
                output_files.append(output_path)
        except Exception as e:
            print(f"Error processing {filepath}: {e}")

    return output_files

# 5. Image Creation
def create_new_image(mode: str, size: Tuple[int, int], color: str = 'white') -> Image.Image:
    """
    Create new image

    Args:
        mode: Image mode ('RGB', 'RGBA', 'L', etc.)
        size: Image size (width, height)
        color: Background color

    Returns:
        New PIL Image
    """
    return Image.new(mode, size, color)

def create_rgb_image(width: int, height: int, color: str = 'white') -> Image.Image:
    """
    Create new RGB image

    Args:
        width: Image width
        height: Image height
        color: Background color

    Returns:
        New RGB Image
    """
    return Image.new('RGB', (width, height), color)

def create_rgba_image(width: int, height: int, color: Tuple[int, int, int, int] = (255, 255, 255, 255)) -> Image.Image:
    """
    Create new RGBA image

    Args:
        width: Image width
        height: Image height
        color: Background color (R, G, B, A)

    Returns:
        New RGBA Image
    """
    return Image.new('RGBA', (width, height), color)

# 6. Image Operations
def rotate_image(image: Image.Image, angle: float, expand: bool = False) -> Image.Image:
    """
    Rotate image

    Args:
        image: PIL Image object
        angle: Rotation angle in degrees
        expand: Expand image to fit rotated content

    Returns:
        Rotated Image
    """
    return image.rotate(angle, expand=expand)

def flip_horizontal(image: Image.Image) -> Image.Image:
    """
    Flip image horizontally

    Args:
        image: PIL Image object

    Returns:
        Flipped Image
    """
    return image.transpose(Image.Transpose.FLIP_LEFT_RIGHT)

def flip_vertical(image: Image.Image) -> Image.Image:
    """
    Flip image vertically

    Args:
        image: PIL Image object

    Returns:
        Flipped Image
    """
    return image.transpose(Image.Transpose.FLIP_TOP_BOTTOM)

def crop_image(image: Image.Image, box: Tuple[int, int, int, int]) -> Image.Image:
    """
    Crop image

    Args:
        image: PIL Image object
        box: Crop box (left, top, right, bottom)

    Returns:
        Cropped Image
    """
    return image.crop(box)

# 7. Thumbnail Generation
def create_thumbnail(image: Image.Image, size: Tuple[int, int]) -> Image.Image:
    """
    Create thumbnail maintaining aspect ratio

    Args:
        image: PIL Image object
        size: Maximum size (width, height)

    Returns:
        Thumbnail Image
    """
    thumbnail = image.copy()
    thumbnail.thumbnail(size)
    return thumbnail

# 8. Image Validation
def is_valid_image(filepath: str) -> bool:
    """
    Check if file is valid image

    Args:
        filepath: Path to file

    Returns:
        True if valid image
    """
    try:
        with Image.open(filepath) as img:
            img.verify()
        return True
    except:
        return False

def get_supported_formats() -> List[str]:
    """
    Get list of supported image formats

    Returns:
        List of format extensions
    """
    return Image.register_extensions.keys()

# Usage Examples
def demonstrate_image_read_save():
    print("=== Web Python Image Read & Save Examples ===\n")

    # Note: These examples demonstrate the API calls
    # In real usage, you would provide actual image file paths

    # 1. Open and save image
    print("--- 1. Open and Save Image ---")
    print("# Open an image")
    print("image = open_image('input.jpg')")
    print("\n# Save as different formats")
    print("save_as_jpg(image, 'output.jpg', quality=95)")
    print("save_as_png(image, 'output.png', optimize=True)")
    print("save_as_gif(image, 'output.gif')")
    print("save_as_bmp(image, 'output.bmp')")

    # 2. Get image information
    print("\n--- 2. Image Information ---")
    print("# Get image metadata")
    print("width = get_image_width(image)")
    print("height = get_image_height(image)")
    print("mode = get_image_mode(image)")
    print("format = get_image_format(image)")
    print("\n# Get all info at once")
    print("info = get_image_info(image)")
    print("print_image_info(image)")

    # 3. Mode conversion
    print("\n--- 3. Mode Conversion ---")
    print("# Convert to different modes")
    print("rgb_image = convert_to_rgb(image)")
    print("rgba_image = convert_to_rgba(image)")
    print("gray_image = convert_to_grayscale(image)")
    print("cmyk_image = convert_mode(image, 'CMYK')")

    # 4. Create new images
    print("\n--- 4. Create New Images ---")
    print("# Create new RGB image")
    print("new_image = create_rgb_image(800, 600, color='white')")
    print("\n# Create new RGBA image with transparency")
    print("new_rgba = create_rgba_image(800, 600, color=(255, 0, 0, 128))")

    # 5. Transformations
    print("\n--- 5. Image Transformations ---")
    print("# Rotate image")
    print("rotated = rotate_image(image, angle=45, expand=True)")
    print("\n# Flip image")
    print("flipped_h = flip_horizontal(image)")
    print("flipped_v = flip_vertical(image)")
    print("\n# Crop image")
    print("cropped = crop_image(image, (100, 100, 500, 500))")

    # 6. Thumbnail
    print("\n--- 6. Thumbnail Generation ---")
    print("# Create thumbnail")
    print("thumbnail = create_thumbnail(image, (150, 150))")
    print("save_as_jpg(thumbnail, 'thumbnail.jpg')")

    # 7. Batch processing
    print("\n--- 7. Batch Processing ---")
    print("# Convert multiple images to PNG")
    print("input_files = ['photo1.jpg', 'photo2.jpg', 'photo3.jpg']")
    print("outputs = batch_convert_format(input_files, 'output_dir/', 'png')")
    print("\n# Resize multiple images")
    print("outputs = batch_resize_save(input_files, 'resized/', (800, 600))")

    # 8. Validation
    print("\n--- 8. Image Validation ---")
    print("# Check if file is valid image")
    print("if is_valid_image('photo.jpg'):")
    print("    print('Valid image')")
    print("\n# Get supported formats")
    print("formats = get_supported_formats()")
    print("print(f'Supported formats: {formats}')")

    # 9. Complete workflow example
    print("\n--- 9. Complete Workflow Example ---")
    print(workflow_example)

    print("\n=== All Image Read & Save Examples Completed ===")

# Example workflow
workflow_example = '''
# Complete image processing workflow
from PIL import Image

def process_image(input_path: str, output_path: str) -> bool:
    """Process image: open, convert, resize, save"""

    # Open image
    image = open_image(input_path)
    if not image:
        print(f"Failed to open {input_path}")
        return False

    # Print info
    print_image_info(image)

    # Convert to RGB if necessary
    if image.mode != 'RGB':
        image = convert_to_rgb(image)

    # Resize to maximum 1920x1080
    thumbnail = create_thumbnail(image, (1920, 1080))

    # Save with quality 85
    success = save_as_jpg(thumbnail, output_path, quality=85)

    return success

# Usage
process_image('input.jpg', 'output.jpg')
'''

# Export functions
export { open_image, save_image }
export { save_as_jpg, save_as_png, save_as_gif, save_as_bmp }
export { get_image_size, get_image_width, get_image_height }
export { get_image_format, get_image_mode, get_image_info, print_image_info }
export { convert_to_rgb, convert_to_rgba, convert_to_grayscale, convert_mode }
export { batch_convert_format, batch_resize_save }
export { create_new_image, create_rgb_image, create_rgba_image }
export { rotate_image, flip_horizontal, flip_vertical, crop_image }
export { create_thumbnail }
export { is_valid_image, get_supported_formats }
export { demonstrate_image_read_save }

💻 Redimensionner une Image python

🟡 intermediate ⭐⭐⭐

Redimensionner des images avec préservation des proportions, dimensions fixes, génération de vignettes et contrôle de la qualité

⏱️ 25 min 🏷️ python, web, image, processing, resize
Prerequisites: Intermediate Python, PIL/Pillow library
# Web Python Image Resize Examples
# Resizing images with various methods and options

# 1. Basic Resizing
from PIL import Image
from typing import Tuple, Optional
import os

def resize_image(image: Image.Image, size: Tuple[int, int], resample: Image.Resampling = Image.Resampling.LANCZOS) -> Image.Image:
    """
    Resize image to exact dimensions

    Args:
        image: PIL Image object
        size: Target size (width, height)
        resample: Resampling filter

    Returns:
        Resized Image
    """
    return image.resize(size, resample)

def resize_width(image: Image.Image, width: int) -> Image.Image:
    """
    Resize image to specific width (maintains aspect ratio)

    Args:
        image: PIL Image object
        width: Target width

    Returns:
        Resized Image
    """
    aspect_ratio = image.height / image.width
    new_height = int(width * aspect_ratio)
    return image.resize((width, new_height), Image.Resampling.LANCZOS)

def resize_height(image: Image.Image, height: int) -> Image.Image:
    """
    Resize image to specific height (maintains aspect ratio)

    Args:
        image: PIL Image object
        height: Target height

    Returns:
        Resized Image
    """
    aspect_ratio = image.width / image.height
    new_width = int(height * aspect_ratio)
    return image.resize((new_width, height), Image.Resampling.LANCZOS)

# 2. Aspect Ratio Preservation
def resize_fit_in_box(image: Image.Image, max_size: Tuple[int, int]) -> Image.Image:
    """
    Resize image to fit within box (maintains aspect ratio)

    Args:
        image: PIL Image object
        max_size: Maximum dimensions (max_width, max_height)

    Returns:
        Resized Image
    """
    max_width, max_height = max_size

    # Calculate scaling factor
    width_ratio = max_width / image.width
    height_ratio = max_height / image.height
    scale = min(width_ratio, height_ratio)

    # Only resize if image is larger
    if scale >= 1:
        return image.copy()

    new_width = int(image.width * scale)
    new_height = int(image.height * scale)

    return image.resize((new_width, new_height), Image.Resampling.LANCZOS)

def resize_fill_box(image: Image.Image, size: Tuple[int, int], background_color: str = 'white') -> Image.Image:
    """
    Resize and crop to fill box (maintains aspect ratio)

    Args:
        image: PIL Image object
        size: Target size (width, height)
        background_color: Background color for letterboxing

    Returns:
        Resized and cropped Image
    """
    target_width, target_height = size

    # Calculate scaling
    width_ratio = target_width / image.width
    height_ratio = target_height / image.height
    scale = max(width_ratio, height_ratio)

    new_width = int(image.width * scale)
    new_height = int(image.height * scale)

    # Resize
    resized = image.resize((new_width, new_height), Image.Resampling.LANCZOS)

    # Create output image
    if image.mode == 'RGBA':
        output = Image.new('RGBA', size, background_color)
    else:
        output = Image.new('RGB', size, background_color)

    # Calculate position to center
    x = (target_width - new_width) // 2
    y = (target_height - new_height) // 2

    # Paste resized image
    output.paste(resized, (x, y))

    return output

def resize_cover_box(image: Image.Image, size: Tuple[int, int]) -> Image.Image:
    """
    Resize and crop to cover box completely (maintains aspect ratio)

    Args:
        image: PIL Image object
        size: Target size (width, height)

    Returns:
        Resized and cropped Image
    """
    target_width, target_height = size

    # Calculate scaling
    width_ratio = target_width / image.width
    height_ratio = target_height / image.height
    scale = max(width_ratio, height_ratio)

    new_width = int(image.width * scale)
    new_height = int(image.height * scale)

    # Resize
    resized = image.resize((new_width, new_height), Image.Resampling.LANCZOS)

    # Calculate crop box
    left = (new_width - target_width) // 2
    top = (new_height - target_height) // 2
    right = left + target_width
    bottom = top + target_height

    return resized.crop((left, top, right, bottom))

# 3. Percentage Resizing
def resize_by_percentage(image: Image.Image, percentage: float) -> Image.Image:
    """
    Resize image by percentage

    Args:
        image: PIL Image object
        percentage: Scale percentage (e.g., 0.5 for 50%)

    Returns:
        Resized Image
    """
    new_width = int(image.width * percentage)
    new_height = int(image.height * percentage)
    return image.resize((new_width, new_height), Image.Resampling.LANCZOS)

def resize_half(image: Image.Image) -> Image.Image:
    """Resize image to 50%"""
    return resize_by_percentage(image, 0.5)

def resize_double(image: Image.Image) -> Image.Image:
    """Resize image to 200%"""
    return resize_by_percentage(image, 2.0)

# 4. Thumbnail Generation
def create_thumbnail(image: Image.Image, size: Tuple[int, int], resample: Image.Resampling = Image.Resampling.LANCZOS) -> Image.Image:
    """
    Create thumbnail maintaining aspect ratio

    Args:
        image: PIL Image object
        size: Maximum size (width, height)
        resample: Resampling filter

    Returns:
        Thumbnail Image
    """
    thumbnail = image.copy()
    thumbnail.thumbnail(size, resample)
    return thumbnail

def create_thumbnail_fit(image: Image.Image, max_width: int, max_height: int) -> Image.Image:
    """
    Create thumbnail that fits within dimensions

    Args:
        image: PIL Image object
        max_width: Maximum width
        max_height: Maximum height

    Returns:
        Thumbnail Image
    """
    return create_thumbnail(image, (max_width, max_height))

# 5. Quality Control
def resize_with_quality(image: Image.Image, size: Tuple[int, int], quality: str = 'high') -> Image.Image:
    """
    Resize with specified quality

    Args:
        image: PIL Image object
        size: Target size
        quality: 'low', 'medium', 'high', 'highest'

    Returns:
        Resized Image
    """
    filters = {
        'low': Image.Resampling.NEAREST,
        'medium': Image.Resampling.BILINEAR,
        'high': Image.Resampling.BICUBIC,
        'highest': Image.Resampling.LANCZOS
    }

    resample = filters.get(quality, Image.Resampling.LANCZOS)
    return image.resize(size, resample)

# 6. Batch Resizing
def batch_resize_images(input_files: list, output_dir: str, size: Tuple[int, int], maintain_aspect: bool = True) -> list:
    """
    Resize multiple images

    Args:
        input_files: List of input file paths
        output_dir: Output directory
        size: Target size
        maintain_aspect: Maintain aspect ratio

    Returns:
        List of output file paths
    """
    os.makedirs(output_dir, exist_ok=True)
    output_files = []

    for filepath in input_files:
        try:
            image = Image.open(filepath)

            if maintain_aspect:
                resized = resize_fit_in_box(image, size)
            else:
                resized = resize_image(image, size)

            basename = os.path.basename(filepath)
            output_path = os.path.join(output_dir, basename)
            resized.save(output_path)
            output_files.append(output_path)

        except Exception as e:
            print(f"Error processing {filepath}: {e}")

    return output_files

def batch_create_thumbnails(input_files: list, output_dir: str, size: Tuple[int, int] = (150, 150)) -> list:
    """
    Create thumbnails for multiple images

    Args:
        input_files: List of input file paths
        output_dir: Output directory
        size: Thumbnail size

    Returns:
        List of output file paths
    """
    os.makedirs(output_dir, exist_ok=True)
    output_files = []

    for filepath in input_files:
        try:
            image = Image.open(filepath)
            thumbnail = create_thumbnail(image, size)

            basename = os.path.basename(filepath)
            name, ext = os.path.splitext(basename)
            output_path = os.path.join(output_dir, f"{name}_thumb{ext}")

            thumbnail.save(output_path)
            output_files.append(output_path)

        except Exception as e:
            print(f"Error processing {filepath}: {e}")

    return output_files

# 7. Smart Resizing
def resize_for_web(image: Image.Image, max_dimension: int = 1920) -> Image.Image:
    """
    Resize image for web use

    Args:
        image: PIL Image object
        max_dimension: Maximum width or height

    Returns:
        Resized Image
    """
    if max(image.width, image.height) > max_dimension:
        return resize_fit_in_box(image, (max_dimension, max_dimension))
    return image.copy()

def resize_for_thumbnail(image: Image.Image, max_dimension: int = 150) -> Image.Image:
    """
    Create optimized thumbnail

    Args:
        image: PIL Image object
        max_dimension: Maximum width or height

    Returns:
        Thumbnail Image
    """
    return create_thumbnail(image, (max_dimension, max_dimension))

def resize_for_social_media(image: Image.Image, platform: str) -> Image.Image:
    """
    Resize for social media platforms

    Args:
        image: PIL Image object
        platform: Platform name ('instagram', 'twitter', 'facebook', 'linkedin')

    Returns:
        Resized Image
    """
    sizes = {
        'instagram': (1080, 1080),
        'twitter': (1200, 675),
        'facebook': (1200, 630),
        'linkedin': (1200, 627)
    }

    size = sizes.get(platform.lower(), (1200, 630))
    return resize_cover_box(image, size)

# 8. Advanced Resizing
def resize_with_padding(image: Image.Image, size: Tuple[int, int], padding_color: str = 'white') -> Image.Image:
    """
    Resize and add padding to fit exact size

    Args:
        image: PIL Image object
        size: Target size
        padding_color: Color of padding

    Returns:
        Resized Image with padding
    """
    resized = resize_fit_in_box(image, size)

    if resized.mode == 'RGBA':
        output = Image.new('RGBA', size, padding_color)
    else:
        output = Image.new('RGB', size, padding_color)

    # Center the resized image
    x = (size[0] - resized.width) // 2
    y = (size[1] - resized.height) // 2
    output.paste(resized, (x, y))

    return output

def resize_step_down(image: Image.Image, size: Tuple[int, int], steps: int = 3) -> Image.Image:
    """
    Resize in multiple steps for better quality

    Args:
        image: PIL Image object
        size: Target size
        steps: Number of resize steps

    Returns:
        Resized Image
    """
    current = image.copy()

    for i in range(steps):
        factor = (steps - i) / steps
        intermediate_width = int(size[0] / factor)
        intermediate_height = int(size[1] / factor)
        current = current.resize((intermediate_width, intermediate_height), Image.Resampling.LANCZOS)

    return current.resize(size, Image.Resampling.LANCZOS)

# Usage Examples
def demonstrate_image_resize():
    print("=== Web Python Image Resize Examples ===\n")

    # API usage demonstrations
    print("--- 1. Basic Resizing ---")
    print("# Resize to exact dimensions")
    print("resized = resize_image(image, (800, 600))")
    print("\n# Resize by width")
    print("resized = resize_width(image, 800)")
    print("\n# Resize by height")
    print("resized = resize_height(image, 600)")

    print("\n--- 2. Aspect Ratio Preservation ---")
    print("# Fit within box")
    print("resized = resize_fit_in_box(image, (800, 600))")
    print("\n# Fill box with background")
    print("resized = resize_fill_box(image, (800, 600), 'white')")
    print("\n# Cover box (crop to fit)")
    print("resized = resize_cover_box(image, (800, 600))")

    print("\n--- 3. Percentage Resizing ---")
    print("# Resize by percentage")
    print("resized = resize_by_percentage(image, 0.5)  # 50%")
    print("resized_half = resize_half(image)")
    print("resized_double = resize_double(image)")

    print("\n--- 4. Thumbnails ---")
    print("# Create thumbnail")
    print("thumbnail = create_thumbnail(image, (150, 150))")
    print("thumbnail_fit = create_thumbnail_fit(image, 150, 150)")

    print("\n--- 5. Quality Control ---")
    print("# Resize with quality")
    print("resized = resize_with_quality(image, (800, 600), quality='high')")
    print("# Quality options: 'low', 'medium', 'high', 'highest'")

    print("\n--- 6. Batch Processing ---")
    print("# Resize multiple images")
    print("files = ['photo1.jpg', 'photo2.jpg']")
    print("outputs = batch_resize_images(files, 'output/', (800, 600))")
    print("\n# Create thumbnails")
    print("thumbnails = batch_create_thumbnails(files, 'thumbs/', (150, 150))")

    print("\n--- 7. Smart Resizing ---")
    print("# Resize for web")
    print("web_image = resize_for_web(image, max_dimension=1920)")
    print("\n# Thumbnail for web")
    print("thumb = resize_for_thumbnail(image, max_dimension=150)")
    print("\n# Social media sizes")
    print("instagram_img = resize_for_social_media(image, 'instagram')")
    print("twitter_img = resize_for_social_media(image, 'twitter')")

    print("\n--- 8. Advanced Resizing ---")
    print("# Resize with padding")
    print("resized = resize_with_padding(image, (800, 600), 'white')")
    print("\n# Multi-step resize for quality")
    print("resized = resize_step_down(image, (400, 300), steps=3)")

    print("\n--- 9. Complete Workflow ---")
    print(complete_workflow)

    print("\n=== All Image Resize Examples Completed ===")

# Complete workflow example
complete_workflow = '''
# Complete image resizing workflow
from PIL import Image

def process_images_for_web(input_dir: str, output_dir: str):
    """Process images for web deployment"""

    # Create output directories
    web_dir = os.path.join(output_dir, 'web')
    thumb_dir = os.path.join(output_dir, 'thumbnails')

    os.makedirs(web_dir, exist_ok=True)
    os.makedirs(thumb_dir, exist_ok=True)

    # Process each image
    for filename in os.listdir(input_dir):
        if filename.lower().endswith(('.jpg', '.jpeg', '.png')):
            input_path = os.path.join(input_dir, filename)

            # Open image
            image = Image.open(input_path)

            # Create web version (max 1920px)
            web_image = resize_for_web(image, 1920)
            web_path = os.path.join(web_dir, filename)
            web_image.save(web_path, quality=85, optimize=True)

            # Create thumbnail (150x150)
            thumbnail = create_thumbnail(image, (150, 150))
            name, ext = os.path.splitext(filename)
            thumb_path = os.path.join(thumb_dir, f"{name}_thumb{ext}")
            thumbnail.save(thumb_path, quality=80, optimize=True)

            print(f"Processed: {filename}")

# Usage
process_images_for_web('input_images/', 'output_images/')
'''

# Export functions
export { resize_image, resize_width, resize_height }
export { resize_fit_in_box, resize_fill_box, resize_cover_box }
export { resize_by_percentage, resize_half, resize_double }
export { create_thumbnail, create_thumbnail_fit }
export { resize_with_quality }
export { batch_resize_images, batch_create_thumbnails }
export { resize_for_web, resize_for_thumbnail, resize_for_social_media }
export { resize_with_padding, resize_step_down }
export { demonstrate_image_resize }

💻 Convertir le Format d'Image python

🟡 intermediate ⭐⭐⭐

Convertir entre formats d'image (JPG, PNG, GIF, BMP) avec conversion d'espace colorimétrique, contrôle de la qualité et gestion de la transparence

⏱️ 30 min 🏷️ python, web, image, processing, convert
Prerequisites: Intermediate Python, PIL/Pillow library
# Web Python Image Format Conversion Examples
# Convert between image formats with color space and quality control

# 1. Basic Format Conversion
from PIL import Image
from typing import Optional, Tuple
import os

def convert_to_jpg(image: Image.Image, output_path: str, quality: int = 95) -> bool:
    """
    Convert image to JPEG format

    Args:
        image: PIL Image object
        output_path: Output file path
        quality: JPEG quality (1-100)

    Returns:
        True if successful
    """
    # Convert to RGB if necessary (JPEG doesn't support transparency)
    if image.mode in ('RGBA', 'LA', 'PA'):
        # Create white background
        background = Image.new('RGB', image.size, (255, 255, 255))
        if image.mode == 'RGBA':
            background.paste(image, mask=image.split()[3])  # Use alpha channel as mask
        else:
            background.paste(image)
        image = background
    elif image.mode != 'RGB':
        image = image.convert('RGB')

    image.save(output_path, 'JPEG', quality=quality, optimize=True)
    return True

def convert_to_png(image: Image.Image, output_path: str, optimize: bool = True) -> bool:
    """
    Convert image to PNG format

    Args:
        image: PIL Image object
        output_path: Output file path
        optimize: Enable PNG optimization

    Returns:
        True if successful
    """
    # PNG supports all modes, but convert RGBA if needed
    if image.mode == 'RGB':
        # No transparency needed
        pass
    elif image.mode not in ('RGBA', 'LA', 'PA'):
        # Ensure mode is supported
        image = image.convert(image.mode if image.mode in ('RGB', 'RGBA') else 'RGB')

    image.save(output_path, 'PNG', optimize=optimize)
    return True

def convert_to_gif(image: Image.Image, output_path: str) -> bool:
    """
    Convert image to GIF format

    Args:
        image: PIL Image object
        output_path: Output file path

    Returns:
        True if successful
    """
    # GIF supports palette mode
    if image.mode not in ('P', 'L'):
        image = image.convert('P')

    image.save(output_path, 'GIF')
    return True

def convert_to_bmp(image: Image.Image, output_path: str) -> bool:
    """
    Convert image to BMP format

    Args:
        image: PIL Image object
        output_path: Output file path

    Returns:
        True if successful
    """
    # BMP doesn't support alpha, convert to RGB
    if image.mode == 'RGBA':
        background = Image.new('RGB', image.size, (255, 255, 255))
        background.paste(image, mask=image.split()[3])
        image = background
    elif image.mode != 'RGB':
        image = image.convert('RGB')

    image.save(output_path, 'BMP')
    return True

def convert_to_webp(image: Image.Image, output_path: str, quality: int = 80, lossless: bool = False) -> bool:
    """
    Convert image to WebP format

    Args:
        image: PIL Image object
        output_path: Output file path
        quality: WebP quality (0-100)
        lossless: Use lossless compression

    Returns:
        True if successful
    """
    image.save(output_path, 'WEBP', quality=quality, lossless=lossless)
    return True

def convert_to_tiff(image: Image.Image, output_path: str) -> bool:
    """
    Convert image to TIFF format

    Args:
        image: PIL Image object
        output_path: Output file path

    Returns:
        True if successful
    """
    image.save(output_path, 'TIFF')
    return True

# 2. Color Space Conversion
def convert_to_rgb(image: Image.Image) -> Image.Image:
    """
    Convert image to RGB color space

    Args:
        image: PIL Image object

    Returns:
        RGB Image
    """
    return image.convert('RGB')

def convert_to_rgba(image: Image.Image, background_color: Tuple[int, int, int] = (255, 255, 255)) -> Image.Image:
    """
    Convert image to RGBA with transparency

    Args:
        image: PIL Image object
        background_color: Background color for non-transparent images

    Returns:
        RGBA Image
    """
    if image.mode == 'RGB':
        # Add alpha channel (fully opaque)
        return image.convert('RGBA')
    elif image.mode == 'RGBA':
        return image
    else:
        # Convert via RGBA
        return image.convert('RGBA')

def convert_to_grayscale(image: Image.Image) -> Image.Image:
    """
    Convert image to grayscale

    Args:
        image: PIL Image object

    Returns:
        Grayscale Image
    """
    return image.convert('L')

def convert_to_cmyk(image: Image.Image) -> Image.Image:
    """
    Convert image to CMYK color space

    Args:
        image: PIL Image object

    Returns:
        CMYK Image
    """
    return image.convert('CMYK')

def convert_mode(image: Image.Image, mode: str) -> Image.Image:
    """
    Convert image to specified mode

    Args:
        image: PIL Image object
        mode: Target mode ('RGB', 'RGBA', 'L', 'CMYK', 'P')

    Returns:
        Converted Image
    """
    return image.convert(mode)

# 3. Quality Control
def convert_jpg_with_quality(image: Image.Image, output_path: str, quality: int = 95) -> bool:
    """
    Convert to JPEG with specified quality

    Args:
        image: PIL Image object
        output_path: Output file path
        quality: Quality level (1-100)

    Returns:
        True if successful
    """
    return convert_to_jpg(image, output_path, quality=quality)

def convert_png_compression(image: Image.Image, output_path: str, compress_level: int = 9) -> bool:
    """
    Convert to PNG with compression

    Args:
        image: PIL Image object
        output_path: Output file path
        compress_level: Compression level (0-9, 9 = max compression)

    Returns:
        True if successful
    """
    if image.mode != 'RGB' and image.mode != 'RGBA':
        image = image.convert('RGB')

    image.save(output_path, 'PNG', compress_level=compress_level)
    return True

def convert_webp_with_settings(image: Image.Image, output_path: str, quality: int = 80, method: int = 6) -> bool:
    """
    Convert to WebP with advanced settings

    Args:
        image: PIL Image object
        output_path: Output file path
        quality: Quality (0-100)
        method: Compression method (0=fast, 6=best)

    Returns:
        True if successful
    """
    image.save(output_path, 'WEBP', quality=quality, method=method)
    return True

# 4. Transparency Handling
def preserve_transparency(image: Image.Image, output_format: str) -> Optional[Image.Image]:
    """
    Prepare image for format conversion while preserving transparency

    Args:
        image: PIL Image object
        output_format: Target format ('jpg', 'png', 'webp')

    Returns:
        Prepared Image or None
    """
    if output_format.lower() == 'jpg':
        # JPEG doesn't support transparency, composite with white background
        if image.mode == 'RGBA':
            background = Image.new('RGB', image.size, (255, 255, 255))
            background.paste(image, mask=image.split()[3])
            return background
        return image.convert('RGB')
    elif output_format.lower() in ('png', 'webp'):
        # These formats support transparency
        if image.mode != 'RGBA':
            return image.convert('RGBA')
        return image
    else:
        return image

def remove_transparency(image: Image.Image, background_color: Tuple[int, int, int] = (255, 255, 255)) -> Image.Image:
    """
    Remove transparency from image

    Args:
        image: PIL Image object
        background_color: Background color

    Returns:
        Image without transparency
    """
    if image.mode == 'RGBA':
        background = Image.new('RGB', image.size, background_color)
        background.paste(image, mask=image.split()[3])
        return background
    return image.convert('RGB')

def add_transparency(image: Image.Image, alpha: int = 128) -> Image.Image:
    """
    Add transparency to image

    Args:
        image: PIL Image object
        alpha: Alpha channel value (0-255)

    Returns:
        RGBA Image with transparency
    """
    if image.mode != 'RGBA':
        image = image.convert('RGBA')

    # Split channels and modify alpha
    r, g, b, a = image.split()
    a = a.point(lambda p: p * alpha // 255)

    # Merge back
    return Image.merge('RGBA', (r, g, b, a))

# 5. Batch Conversion
def batch_convert_format(input_files: list, output_dir: str, output_format: str, **kwargs) -> list:
    """
    Convert multiple images to specified format

    Args:
        input_files: List of input file paths
        output_dir: Output directory
        output_format: Target format ('jpg', 'png', 'gif', 'bmp', 'webp')
        **kwargs: Additional format-specific options

    Returns:
        List of output file paths
    """
    os.makedirs(output_dir, exist_ok=True)
    output_files = []

    converters = {
        'jpg': convert_to_jpg,
        'jpeg': convert_to_jpg,
        'png': convert_to_png,
        'gif': convert_to_gif,
        'bmp': convert_to_bmp,
        'webp': convert_to_webp,
        'tiff': convert_to_tiff
    }

    converter = converters.get(output_format.lower())
    if not converter:
        raise ValueError(f"Unsupported format: {output_format}")

    for filepath in input_files:
        try:
            image = Image.open(filepath)

            # Determine output path
            basename = os.path.basename(filepath)
            name = os.path.splitext(basename)[0]
            output_path = os.path.join(output_dir, f"{name}.{output_format}")

            # Convert
            if output_format.lower() in ('jpg', 'jpeg'):
                converter(image, output_path, quality=kwargs.get('quality', 95))
            elif output_format.lower() == 'webp':
                converter(image, output_path, quality=kwargs.get('quality', 80))
            else:
                converter(image, output_path)

            output_files.append(output_path)

        except Exception as e:
            print(f"Error converting {filepath}: {e}")

    return output_files

def batch_convert_with_color_space(input_files: list, output_dir: str, output_format: str, color_mode: str = 'RGB') -> list:
    """
    Convert images with color space transformation

    Args:
        input_files: List of input file paths
        output_dir: Output directory
        output_format: Target format
        color_mode: Target color mode ('RGB', 'RGBA', 'L', 'CMYK')

    Returns:
        List of output file paths
    """
    os.makedirs(output_dir, exist_ok=True)
    output_files = []

    for filepath in input_files:
        try:
            image = Image.open(filepath)

            # Convert color space
            image = convert_mode(image, color_mode)

            # Save in target format
            basename = os.path.basename(filepath)
            name = os.path.splitext(basename)[0]
            output_path = os.path.join(output_dir, f"{name}.{output_format}")

            image.save(output_path)
            output_files.append(output_path)

        except Exception as e:
            print(f"Error converting {filepath}: {e}")

    return output_files

# 6. Optimization
def optimize_image_size(image: Image.Image, output_path: str, max_size_kb: int, format: str = 'jpg') -> bool:
    """
    Convert with size constraint

    Args:
        image: PIL Image object
        output_path: Output file path
        max_size_kb: Maximum file size in KB
        format: Output format

    Returns:
        True if successful
    """
    quality = 95
    min_quality = 10

    while quality >= min_quality:
        from io import BytesIO

        # Save to memory
        buffer = BytesIO()
        if format.lower() == 'jpg':
            image.save(buffer, format='JPEG', quality=quality, optimize=True)
        elif format.lower() == 'png':
            image.save(buffer, format='PNG', optimize=True)
        elif format.lower() == 'webp':
            image.save(buffer, format='WEBP', quality=quality)

        # Check size
        size_kb = len(buffer.getvalue()) / 1024
        if size_kb <= max_size_kb:
            # Save to file
            with open(output_path, 'wb') as f:
                f.write(buffer.getvalue())
            return True

        # Reduce quality
        quality -= 5

    return False

# 7. Special Conversions
def convert_to_black_white(image: Image.Image) -> Image.Image:
    """
    Convert to black and white (1-bit)

    Args:
        image: PIL Image object

    Returns:
        Black and white Image
    """
    return image.convert('1')

def convert_to_palette(image: Image.Image, colors: int = 256) -> Image.Image:
    """
    Convert to palette mode

    Args:
        image: PIL Image object
        colors: Number of colors

    Returns:
        Palette Image
    """
    return image.convert('P', palette=Image.Palette.ADAPTIVE, colors=colors)

def convert_with_icc_profile(image: Image.Image, output_path: str, icc_profile_path: str) -> bool:
    """
    Convert with ICC color profile

    Args:
        image: PIL Image object
        output_path: Output file path
        icc_profile_path: Path to ICC profile

    Returns:
        True if successful
    """
    try:
        image.save(output_path, icc_profile=icc_profile_path)
        return True
    except:
        return False

# Usage Examples
def demonstrate_image_format_convert():
    print("=== Web Python Image Format Conversion Examples ===\n")

    print("--- 1. Basic Format Conversion ---")
    print("# Convert to JPEG")
    print("convert_to_jpg(image, 'output.jpg', quality=95)")
    print("\n# Convert to PNG")
    print("convert_to_png(image, 'output.png', optimize=True)")
    print("\n# Convert to WebP")
    print("convert_to_webp(image, 'output.webp', quality=80)")
    print("\n# Convert to GIF")
    print("convert_to_gif(image, 'output.gif')")

    print("\n--- 2. Color Space Conversion ---")
    print("# Convert color spaces")
    print("rgb_img = convert_to_rgb(image)")
    print("rgba_img = convert_to_rgba(image)")
    print("gray_img = convert_to_grayscale(image)")
    print("cmyk_img = convert_to_cmyk(image)")

    print("\n--- 3. Quality Control ---")
    print("# JPEG with quality")
    print("convert_jpg_with_quality(image, 'output.jpg', quality=85)")
    print("\n# PNG with compression")
    print("convert_png_compression(image, 'output.png', compress_level=9)")
    print("\n# WebP with settings")
    print("convert_webp_with_settings(image, 'output.webp', quality=80, method=6)")

    print("\n--- 4. Transparency Handling ---")
    print("# Preserve transparency for PNG/WebP")
    print("prepared = preserve_transparency(image, 'png')")
    print("\n# Remove transparency for JPEG")
    print("no_alpha = remove_transparency(image, (255, 255, 255))")
    print("\n# Add transparency")
    print("with_alpha = add_transparency(image, alpha=128)")

    print("\n--- 5. Batch Conversion ---")
    print("# Convert all to JPEG")
    print("files = ['photo1.png', 'photo2.png']")
    print("outputs = batch_convert_format(files, 'output/', 'jpg', quality=85)")
    print("\n# Convert with color space")
    print("outputs = batch_convert_with_color_space(files, 'output/', 'jpg', 'RGB')")

    print("\n--- 6. Optimization ---")
    print("# Optimize for size constraint")
    print("optimize_image_size(image, 'output.jpg', max_size_kb=500)")

    print("\n--- 7. Special Conversions ---")
    print("# Black and white")
    print("bw = convert_to_black_white(image)")
    print("\n# Palette mode")
    print("palette = convert_to_palette(image, colors=256)")

    print("\n--- 8. Complete Workflow ---")
    print(complete_workflow)

    print("\n=== All Image Format Conversion Examples Completed ===")

# Complete workflow
complete_workflow = '''
# Complete image conversion workflow
from PIL import Image

def convert_for_web(input_path: str, output_dir: str):
    """Convert image for web with multiple formats"""

    # Open image
    image = Image.open(input_path)

    # Create output directory
    os.makedirs(output_dir, exist_ok=True)

    # Get base name
    basename = os.path.splitext(os.path.basename(input_path))[0]

    # 1. High-quality JPEG for general use
    convert_to_jpg(image, os.path.join(output_dir, f'{basename}.jpg'), quality=95)

    # 2. PNG with transparency if needed
    if image.mode == 'RGBA':
        convert_to_png(image, os.path.join(output_dir, f'{basename}.png'))

    # 3. WebP for modern browsers
    convert_to_webp(image, os.path.join(output_dir, f'{basename}.webp'), quality=85)

    # 4. Optimized JPEG (smaller file)
    optimize_image_size(image, os.path.join(output_dir, f'{basename}_small.jpg'), max_size_kb=200)

    print(f"Converted: {basename}")

# Usage
convert_for_web('input.png', 'web_output/')
'''

# Export functions
export { convert_to_jpg, convert_to_png, convert_to_gif, convert_to_bmp }
export { convert_to_webp, convert_to_tiff }
export { convert_to_rgb, convert_to_rgba, convert_to_grayscale, convert_to_cmyk, convert_mode }
export { convert_jpg_with_quality, convert_png_compression, convert_webp_with_settings }
export { preserve_transparency, remove_transparency, add_transparency }
export { batch_convert_format, batch_convert_with_color_space }
export { optimize_image_size }
export { convert_to_black_white, convert_to_palette, convert_with_icc_profile }
export { demonstrate_image_format_convert }