Skip to main content

Intelligent image compression library with perceptual quality optimization

Project description

๐ŸŽจ Pixiq - Smart Image Compression

Intelligently compress images while preserving visual quality

Python Version License Tests

Compress smarter, not harder. Let AI choose the perfect quality for your images.

๐Ÿ“ฆ Installation โ€ข ๐Ÿš€ Quick Start โ€ข ๐Ÿ“š Documentation โ€ข โ“ Why Pixiq?


โœจ Key Features

๐ŸŽฏ Smart Quality Selection - Automatically finds the optimal compression quality to match your target visual quality

๐Ÿ–ผ๏ธ Multiple Formats - Supports JPEG, PNG, WEBP, and AVIF with format-specific optimizations

๐Ÿ“ Intelligent Resizing - Resize images while maintaining aspect ratio and quality

๐Ÿ”„ Thumbnail Generation - Create smaller versions of compressed images instantly

๐ŸŽจ Alpha Channel Support - Handles transparent images correctly for each format

โšก Performance Optimized - Fast compression with efficient memory usage

๐Ÿ›ก๏ธ Robust Validation - Comprehensive input validation and error handling

๐Ÿ” Quality Metrics - Detailed compression statistics and iteration info


๐Ÿ“ฆ Installation

From PyPI (Recommended)

Using uv (fastest):

uv add pixiq
# or
uv pip install pixiq

Using pip:

pip install pixiq

From Source

git clone https://github.com/yourusername/pixiq.git
cd pixiq

# Using uv
uv sync --dev
uv pip install -e .

# Using pip
pip install -e .

Requirements

  • Python 3.9+
  • PIL (Pillow) - Image processing
  • NumPy - Array operations
  • pillow-avif-plugin - AVIF format support

๐Ÿ’ก Tip: uv is significantly faster than pip and provides better dependency management.


๐Ÿš€ Quick Start

Try it now! Run the interactive demo:

python example.py

Basic Compression

from PIL import Image
from pixiq import Pixiq

# Open your image
image = Image.open('photo.jpg')

# Compress with target quality
result = Pixiq.compress(image, perceptual_quality=0.9)

print(f"โœ… Compressed! Size: {result.file_size_kb:.1f} KB, Quality: {result.selected_quality}")

Advanced Usage

# Compress with custom settings
result = Pixiq.compress(
    input=image,
    perceptual_quality=0.85,    # Target visual quality (0.0-1.0)
    max_size=2000,             # Resize if larger than 2000px
    format='WEBP',             # Force WEBP format
    hash_type='sha1',          # Use SHA1 instead of default SHA256
    output='compressed.webp'   # Save to file
)

# Access compression details
print(f"๐Ÿ“Š Quality: {result.selected_quality}/100")
print(f"๐Ÿ“ Dimensions: {result.dimensions}")
print(f"๐Ÿ’พ Size: {result.file_size_kb:.1f} KB")
print(f"๐Ÿ” Hash ({result.hash_type}): {result.hash}")
print(f"๐ŸŽฏ Achieved quality: {result.best_iteration['perceptual_quality']:.3f}")

Thumbnail Generation

# Create a thumbnail from compressed image
thumbnail = result.save_thumbnail(
    max_size=500,
    output='thumbnail.webp'
)

print(f"๐Ÿ–ผ๏ธ Thumbnail: {thumbnail.dimensions}, {thumbnail.file_size_kb:.1f} KB")

๐Ÿ“š API Reference

Pixiq.compress() โšก

The main method for intelligent image compression with automatic quality selection.

Parameters

Parameter Type Default Description
input PIL Image required Input image to compress
perceptual_quality float 0.95 Target visual quality (0.0-1.0)
tolerance float 0.005 Quality tolerance for convergence
max_quality int None Maximum compression quality (1-100)
min_quality int None Minimum compression quality (1-100)
max_size int None Maximum dimension (resizes if larger)
max_iter int 5 Maximum binary search iterations
format str None Force format: 'JPEG', 'PNG', 'WEBP', 'AVIF'
hash_type str 'sha256' Hash algorithm: 'sha1', 'sha256', etc.
output str/BytesIO None Output file path or buffer

Returns

CompressionResult - Object containing compressed image and metadata

Exceptions

  • TypeError - Invalid parameter types
  • ValueError - Parameter values out of range
  • OSError - File I/O errors

CompressionResult ๐Ÿ“Š

Container for compression results with convenient access methods.

Core Properties

Property Type Description
compressed PIL Image The compressed image
iterations_count int Number of compression attempts
iterations_info List[dict] Detailed info for each iteration
selected_quality int Final compression quality (1-100)
hash str Hash of compressed image (SHA1/SHA256)
hash_type str Hash algorithm used ('sha1', 'sha256')
file_size int File size in bytes
fmt str Image format ('jpeg', 'webp', etc.)
extra_save_args dict Format-specific save parameters

Computed Properties

Property Type Description
file_size_kb float File size in kilobytes
dimensions tuple[int, int] Image dimensions (width, height)
best_iteration dict | None Info about best quality match

Methods

save(output) ๐Ÿ’พ

Save compressed image to file or buffer.

result.save('output.webp')
result.save(io.BytesIO())
save_thumbnail(max_size, output=None) ๐Ÿ–ผ๏ธ

Create and save a resized version of the compressed image.

thumbnail = result.save_thumbnail(max_size=500, output='thumb.webp')

Returns: New CompressionResult with resized image


๐ŸŽจ Supported Formats

Format Extension Alpha Support Optimization
JPEG .jpg, .jpeg โŒ Progressive, optimized
PNG .png โœ… Lossless compression
WEBP .webp โœ… Method 6 (max compression)
AVIF .avif โœ… Speed 6 (balanced)

๐Ÿ’ก Tip: Pixiq automatically detects format from file extension or uses JPEG as fallback


๐Ÿง  How It Works

Pixiq uses a smart binary search algorithm to find the optimal compression quality:

  1. ๐ŸŽฏ Quality Search - Binary search over quality range (1-100) to find optimal compression
  2. ๐Ÿ“Š PSNR Analysis - Calculate Peak Signal-to-Noise Ratio between original and compressed images
  3. ๐Ÿง  Perceptual Mapping - Convert PSNR to perceptual quality using empirical formula
  4. ๐ŸŽช Best Match Selection - Choose quality with minimum error from target perceptual quality
  5. ๐Ÿ”— Efficient Hashing - Generate SHA1/SHA256 hash from compressed data without re-encoding

Algorithm Visualization

Target Quality: 0.85
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ Quality 1 โ”€โ”€โ”€โ”€โ–บ Quality 100         โ”‚
โ”‚     โ†“              โ†“              โ†“ โ”‚
โ”‚  PSNR: 25.3     PSNR: 35.7      PSNR: 42.1 โ”‚
โ”‚  Perceptual: 0.3 โ”€โ”€โ”€โ”€โ–บ 0.8 โ”€โ”€โ”€โ”€โ–บ 0.95 โ”‚
โ”‚     โ”‚              โ”‚              โ”‚ โ”‚
โ”‚     โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚
โ”‚                    โ–ผ                โ”‚
โ”‚              โœ… Best Match          โ”‚
โ”‚              Quality: 67            โ”‚
โ”‚              Error: 0.0012          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

โ“ Why Pixiq?

๐Ÿ” The Problem

Traditional image compression requires manual quality tuning:

# Old way - guesswork required
image.save('output.jpg', quality=85)  # Is 85 good enough?
image.save('output.jpg', quality=75)  # Too low quality?
image.save('output.jpg', quality=80)  # Still guessing...

โœ… The Solution

Pixiq automatically finds the perfect quality for your needs:

# New way - specify what you want
result = Pixiq.compress(image, perceptual_quality=0.9)
# Automatically finds quality=67 for 90% perceptual quality!

๐Ÿš€ Performance Benefits

Feature Traditional Pixiq
Quality Control Manual guesswork Precise target quality
File Size Variable, unpredictable Optimal for quality target
Time Multiple manual attempts Single API call
Consistency Depends on user expertise Consistent, reproducible
Formats One quality per format Optimized per format

๐Ÿ“ˆ Real-World Results

Original: photo.jpg (2.3 MB, 4000x3000)
Target: 85% perceptual quality

Format    Quality    Size     Time
JPEG      78         245 KB   0.8s
WEBP      82         198 KB   0.7s
AVIF      75         156 KB   1.2s

๐Ÿงช Testing

Run the comprehensive test suite:

# Install development dependencies (using uv - recommended)
uv sync --dev

# Or using pip
pip install -e ".[dev]"

# Run tests
uv run pytest tests/

# Or using pytest directly
pytest tests/

# Or run manually
python -c "from tests.test_pixiq import *; test_basic_compression()"

๐Ÿ’ก Tip: Using uv sync --dev is the fastest way to set up the development environment!


๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide for details.

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Ensure all tests pass
  5. Submit a pull request

๐Ÿ“„ License

MIT License - see LICENSE file for details.


๐Ÿ™ Acknowledgments

  • Built with Pillow for image processing
  • Uses NumPy for efficient array operations
  • Powered by uv for lightning-fast package management
  • Inspired by modern image optimization techniques

Made with โค๏ธ for developers who care about image quality

โญ Star us on GitHub โ€ข ๐Ÿ› Report Issues โ€ข ๐Ÿ’ฌ Join Discussions

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pixiq-0.3.2.tar.gz (46.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pixiq-0.3.2-py3-none-any.whl (11.0 kB view details)

Uploaded Python 3

File details

Details for the file pixiq-0.3.2.tar.gz.

File metadata

  • Download URL: pixiq-0.3.2.tar.gz
  • Upload date:
  • Size: 46.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.7

File hashes

Hashes for pixiq-0.3.2.tar.gz
Algorithm Hash digest
SHA256 ec78e29092917d60400fac3af427fe315aeb4046c6242bf95ca4ca263ad4a622
MD5 908f772a8a687fe783d73e7b938479f5
BLAKE2b-256 bd6154b461307e87bc6a5a3cac760cae376e8d706c293e825047772e52525e48

See more details on using hashes here.

File details

Details for the file pixiq-0.3.2-py3-none-any.whl.

File metadata

  • Download URL: pixiq-0.3.2-py3-none-any.whl
  • Upload date:
  • Size: 11.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.7

File hashes

Hashes for pixiq-0.3.2-py3-none-any.whl
Algorithm Hash digest
SHA256 c318297a2fe563e50429982fe20b055a6a83d44d7d958e16b34f53d11569ac7c
MD5 2a27c0da885bb1142d9007fadb4dbd52
BLAKE2b-256 80390280a2a705104583757303718091077f5dc7d9afd864d46123bfdfcb535a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page