ComfyUI Extension: AC Image Optimizer

Authored by abdullahceylan

Created

Updated

0 stars

A powerful ComfyUI custom node for optimizing and compressing images with support for multiple formats (JPEG, WebP, PNG) and configurable quality settings.

Custom Nodes (0)

    README

    AC Image Optimizer - ComfyUI Custom Node

    A powerful ComfyUI custom node for optimizing and compressing images with support for multiple formats (JPEG, WebP, PNG) and configurable quality settings.

    Features

    • Multiple Formats: JPEG, WebP, PNG support
    • Quality Control: Adjustable quality from 1-100
    • Real-time Statistics: View compression ratios and file sizes
    • Advanced Mode: Format comparison and debug output
    • Batch Processing: Works with ComfyUI's batch processing
    • Optimized Performance: Built on PIL with efficient compression

    Installation

    1. Navigate to your ComfyUI custom nodes directory:
    cd ComfyUI/custom_nodes/
    
    1. Clone or copy this repository:
    git clone https://github.com/abdullahceylan/ac-comfyui-image-optimizer
    # or
    cp -r ac-image-optimizer ComfyUI/custom_nodes/
    
    1. Restart ComfyUI

    Nodes

    1. AC Image Optimizer (Basic)

    Simple image optimization node with essential controls.

    Inputs:

    • image (IMAGE): Input image to optimize
    • format (JPEG/WEBP/PNG): Output image format
    • quality (1-100): Compression quality (higher = better quality, larger file)
    • optimize (BOOLEAN): Enable additional optimization passes

    Outputs:

    • image (IMAGE): Optimized image
    • stats (STRING): Compression statistics (format, size, reduction %)

    Example Usage:

    Load Image → AC Image Optimizer → Preview Image
    

    ⚠️ Important Note: This node optimizes the image but returns it as a tensor for preview. If you use ComfyUI's standard "Save Image" node, it will save as PNG (ComfyUI's default). Use "AC Image Optimizer & Save" instead to save in the correct format.

    Recommended Settings:

    • For web display: JPEG, quality 85
    • For high quality: JPEG, quality 90-95
    • For smallest size: WebP, quality 75-85
    • For lossless: PNG (quality ignored)

    2. AC Image Optimizer & Save ⭐ RECOMMENDED

    Optimizes AND saves the image directly in the correct format. This solves the issue where ComfyUI's Save Image node always saves as PNG.

    Inputs:

    • image (IMAGE): Input image to optimize
    • format (JPEG/WEBP/PNG): Output format for saved file
    • quality (1-100): Compression quality
    • filename_prefix (STRING): Prefix for saved filename (e.g., "optimized")

    Outputs:

    • image (IMAGE): Optimized image (for preview)
    • save_info (STRING): Save confirmation with file location and stats

    Example Usage:

    Load Image → AC Image Optimizer & Save → Preview Image
                                            (optional - already saved!)
    

    Benefits:

    • ✅ Saves directly in the format you choose (JPEG/WebP/PNG)
    • ✅ Maintains the compression and optimization
    • ✅ No need for separate Save Image node
    • ✅ Auto-increments filename to avoid overwriting
    • ✅ Shows where the file was saved

    Output Location: ComfyUI/output/ directory with filenames like optimized_00001.jpg

    3. AC Image Optimizer Advanced

    Advanced optimization with format comparison and debug capabilities.

    Inputs:

    • image (IMAGE): Input image to optimize
    • primary_format (JPEG/WEBP/PNG): Primary output format
    • quality (1-100): Compression quality
    • enable_debug (BOOLEAN): Save debug comparison images
    • debug_prefix (STRING, optional): Prefix for debug filenames

    Outputs:

    • image (IMAGE): Optimized image in primary format
    • comparison_stats (STRING): Detailed comparison of JPEG vs WebP

    Debug Output: When enable_debug is enabled, saves comparison images to:

    ComfyUI/output/ac_image_optimizer_debug/
      ├── {prefix}_1_original.png
      ├── {prefix}_2_compressed.jpg
      └── {prefix}_3_compressed.webp
    

    Example Usage:

    Load Image → AC Image Optimizer Advanced → Preview Image
                                              └→ Save Image
    

    Quality Presets

    | Preset | Quality | Use Case | |--------|---------|----------| | High | 95 | Maximum quality, larger files | | Good | 85 | Recommended - Best balance | | Medium | 75 | Good quality, smaller files | | Low | 60 | Maximum compression |

    Format Comparison

    | Format | Pros | Cons | Best For | |--------|------|------|----------| | JPEG | Universal support, good compression | Lossy, no transparency | Photos, general images | | WebP | Better compression than JPEG | Limited older browser support | Web display, modern apps | | PNG | Lossless, transparency support | Larger file sizes | Graphics, logos, masks |

    Typical Compression Results

    Example 1: Generated Image (1024x1024)

    • Original PNG: 2.3 MB
    • JPEG (q=85): 83 KB (96% reduction)
    • WebP (q=85): 52 KB (98% reduction)

    Example 2: High Resolution Photo (2048x2048)

    • Original PNG: 8.5 MB
    • JPEG (q=90): 420 KB (95% reduction)
    • WebP (q=90): 285 KB (97% reduction)

    Workflow Examples

    Basic Workflow

    ┌─────────────┐     ┌───────────────────┐     ┌────────────┐
    │ Load Image  │────▶│ AC Image Optimizer│────▶│ Save Image │
    └─────────────┘     │  format: JPEG     │     └────────────┘
                        │  quality: 85      │
                        └───────────────────┘
    

    Advanced Workflow with Comparison

    ┌─────────────┐     ┌─────────────────────────┐     ┌────────────────┐
    │ Load Image  │────▶│ AC Image Optimizer Adv  │────▶│ Preview Image  │
    └─────────────┘     │  primary: JPEG          │     └────────────────┘
                        │  quality: 85            │             │
                        │  debug: True            │             ▼
                        └─────────────────────────┘     ┌────────────────┐
                                  │                     │ Display Stats  │
                                  └────────────────────▶└────────────────┘
    

    Batch Processing

    ┌─────────────┐     ┌───────────────────┐     ┌───────────────┐     ┌────────────┐
    │ Load Images │────▶│ AC Image Optimizer│────▶│ Batch Process │────▶│ Save Batch │
    │   (Batch)   │     │  format: WEBP     │     └───────────────┘     └────────────┘
    └─────────────┘     │  quality: 80      │
                        └───────────────────┘
    

    Integration with Other Nodes

    Example: Optimize After Upscaling

    Load Image → Upscaler → AC Image Optimizer → Save Image
                            (JPEG, q=90)
    

    Example: Optimize Before API Send

    Load Image → AC Image Optimizer → Base64 Encode → API Call
                 (JPEG, q=85)
    

    Example: Compare Formats

    Load Image → AC Image Optimizer Advanced → Preview Stats
                 (enable_debug: True)
                 
    Check: ComfyUI/output/ac_image_optimizer_debug/
    

    Technical Details

    Image Processing Pipeline

    1. Input: ComfyUI image tensor (B, H, W, C) in [0, 1] range
    2. Convert: Tensor → PIL Image
    3. Optimize: PIL Image → Compressed buffer (using utils/image_optimization.py)
    4. Convert Back: Compressed buffer → PIL Image → Tensor
    5. Output: Optimized tensor + statistics

    Supported Color Modes

    • RGB (most common)
    • RGBA (converted to RGB for JPEG)
    • Grayscale (preserved)

    Dependencies

    • Python 3.8+
    • PyTorch
    • Pillow (PIL)
    • NumPy

    Troubleshooting

    Issue: Saved image is still PNG/large file size ⚠️

    Problem: Using "AC Image Optimizer" with ComfyUI's "Save Image" node saves as PNG.

    Why: ComfyUI's Save Image node always saves tensors as PNG by default, losing your optimization.

    Solution: Use "AC Image Optimizer & Save" node instead! This saves directly in your chosen format.

    ❌ Bad:  Load Image → AC Image Optimizer → Save Image (saves as PNG!)
    ✅ Good: Load Image → AC Image Optimizer & Save (saves as JPEG/WebP!)
    

    Issue: Node not appearing in ComfyUI

    Solution:

    1. Check that the folder is in ComfyUI/custom_nodes/
    2. Restart ComfyUI completely
    3. Check console for any error messages

    Issue: "Module not found" error

    Solution: Ensure all dependencies are installed:

    pip install torch pillow numpy
    

    Issue: Images appear corrupted

    Solution:

    1. Try increasing quality to 90+
    2. Check input image is valid
    3. Try different format (PNG for lossless)

    Issue: Debug files not saving

    Solution:

    1. Ensure enable_debug is True
    2. Check write permissions in ComfyUI/output/
    3. Verify the output directory exists

    Performance Tips

    1. Use JPEG for photos: Better compression than PNG
    2. Use WebP for smallest files: Up to 30% smaller than JPEG
    3. Quality 85 is optimal: Good balance of quality and size
    4. Enable optimize: Minimal speed impact, better compression
    5. Use PNG only when needed: For transparency or lossless

    Development

    Project Structure

    ac-image-optimizer/
    ├── __init__.py                 # Main node definitions
    ├── utils/
    │   ├── __init__.py
    │   ├── image_optimization.py   # Core optimization utilities
    │   └── IMAGE_OPTIMIZATION_USAGE.md
    └── README.md                   # This file
    

    Extending the Node

    To add custom functionality, extend the base classes:

    from . import ACImageOptimizer
    
    class MyCustomOptimizer(ACImageOptimizer):
        @classmethod
        def INPUT_TYPES(cls):
            inputs = super().INPUT_TYPES()
            inputs["required"]["my_param"] = ("INT", {"default": 10})
            return inputs
        
        def optimize_image(self, image, format, quality, optimize, my_param):
            # Your custom logic
            return super().optimize_image(image, format, quality, optimize)
    

    License

    MIT License - see LICENSE file for details

    Copyright (c) 2025 Abdullah Ceylan

    Support

    For issues, questions, or contributions:

    • GitHub Issues: [Add your repo link]
    • Email: [Add your email]

    Changelog

    v1.0.0 (Initial Release)

    • Basic image optimization node
    • Advanced node with format comparison
    • Support for JPEG, WebP, PNG
    • Configurable quality settings
    • Debug output mode
    • Compression statistics