> ## Documentation Index
> Fetch the complete documentation index at: https://docs.imperial.gay/llms.txt
> Use this file to discover all available pages before exploring further.

# Auto Compression

> How Imperial automatically optimizes your images to save storage

## What is Auto Compression?

Auto compression automatically reduces image file sizes during upload while maintaining visual quality. This saves storage space and makes images load faster for your users.

<Info>
  Compression is optional and can be configured in your [Dashboard
  Settings](https://app.imperial.gay/settings).
</Info>

## How It Works

When you upload an image with auto-compression enabled:

<Steps>
  <Step title="Upload Detection">
    Imperial receives your image and detects its format (JPEG, PNG, WebP)
  </Step>

  <Step title="Quality Analysis">
    The image is analyzed to determine the optimal compression settings
  </Step>

  <Step title="Smart Compression">
    Using Sharp (high-performance image processing), the image is recompressed with your quality
    setting
  </Step>

  <Step title="Size Verification">
    If compression makes the file larger (rare), the original is kept instead
  </Step>

  <Step title="Storage & Delivery">The optimized image is stored and delivered via CDN</Step>
</Steps>

## Supported Formats

<Tabs>
  <Tab title="JPEG">
    **Best for**: Photos, complex images with gradients - Default quality: 80% - Typical savings:
    40-60% - Maintains color accuracy - Uses optimized encoding (Progressive JPEG) `Original:
            cat.jpg (2.4 MB) Compressed: cat.jpg (960 KB) - 60% smaller ✨`
  </Tab>

  <Tab title="PNG">
    **Best for**: Screenshots, graphics with transparency - Compression level: 9 (maximum) - Typical
    savings: 20-40% - Preserves transparency - Uses optimized palette when possible `Original:
            logo.png (1.2 MB) Compressed: logo.png (840 KB) - 30% smaller ✨`
  </Tab>

  <Tab title="WebP">
    **Best for**: Modern web applications - Default quality: 80% - Typical savings: 50-70% vs JPEG -
    Supports transparency - Better compression than PNG/JPEG `Original: image.webp (800 KB)
            Compressed: image.webp (280 KB) - 65% smaller ✨`
  </Tab>
</Tabs>

<Warning>
  **Videos are never compressed** to preserve quality and avoid long processing times. Video
  compression is complex and best done before upload with tools like FFmpeg.
</Warning>

## Quality Settings

You can customize the compression quality in your dashboard:

| Quality | File Size    | Visual Quality   | Best For                 |
| ------- | ------------ | ---------------- | ------------------------ |
| 60%     | Smallest     | Noticeable loss  | Thumbnails, previews     |
| 70%     | Very Small   | Slight loss      | Web images, social media |
| **80%** | **Balanced** | **Minimal loss** | **Default, recommended** |
| 90%     | Larger       | Nearly perfect   | Professional photography |
| 100%    | Largest      | Perfect          | Original archival        |

<Tip>
  **80% quality** is the sweet spot - most users can't tell the difference from 100%, but files are
  40-60% smaller.
</Tip>

## Technical Implementation

Imperial uses **Sharp**, the industry-standard high-performance image processing library:

### Why Sharp?

<CardGroup cols={2}>
  <Card title="Fast Processing" icon="bolt">
    4-5x faster than ImageMagick Uses libvips for efficient memory usage
  </Card>

  <Card title="High Quality" icon="star">
    Professional-grade algorithms Maintains color profiles and metadata
  </Card>

  <Card title="Memory Efficient" icon="microchip">
    Streams data instead of loading full images Can process images larger than RAM
  </Card>

  <Card title="Modern Formats" icon="image">
    Supports WebP, AVIF, JPEG XL Future-proof for new formats
  </Card>
</CardGroup>

### Compression Algorithm

```javascript theme={null}
// Simplified version of Imperial's compression logic
async function compressImage(buffer, mimeType, quality = 80) {
  const sharpInstance = sharp(buffer);

  switch (mimeType) {
    case "image/jpeg":
      return await sharpInstance
        .jpeg({
          quality,
          progressive: true, // Better for web loading
          optimizeScans: true, // Optimal scan compression
          chromaSubsampling: "4:2:0", // Standard subsampling
        })
        .toBuffer();

    case "image/png":
      return await sharpInstance
        .png({
          quality,
          compressionLevel: 9, // Maximum compression
          adaptiveFiltering: true, // Better compression
          palette: true, // Use indexed color if possible
        })
        .toBuffer();

    case "image/webp":
      return await sharpInstance
        .webp({
          quality,
          effort: 4, // Balance speed vs compression
          smartSubsample: true, // Better quality at edges
        })
        .toBuffer();
  }
}
```

## Real-World Examples

### Example 1: Product Photos

```
Original JPEG (iPhone 14 Pro Max):
├─ Resolution: 4032 × 3024
├─ File size: 3.8 MB
└─ Quality: 100%

After 80% Compression:
├─ Resolution: 4032 × 3024 (unchanged)
├─ File size: 1.4 MB (63% smaller)
└─ Quality: Visually identical
```

### Example 2: Screenshots

```
Original PNG (4K monitor):
├─ Resolution: 3840 × 2160
├─ File size: 2.2 MB
└─ Colors: 16.7 million

After Compression:
├─ Resolution: 3840 × 2160 (unchanged)
├─ File size: 1.6 MB (27% smaller)
└─ Colors: Optimized palette
```

### Example 3: Web Graphics

```
Original WebP (design export):
├─ Resolution: 1920 × 1080
├─ File size: 890 KB
└─ Transparency: Yes

After 80% Compression:
├─ Resolution: 1920 × 1080 (unchanged)
├─ File size: 310 KB (65% smaller)
└─ Transparency: Preserved
```

## When to Use Compression

<AccordionGroup>
  <Accordion title="✅ Great For">
    * **Web Images**: Photos, banners, backgrounds - **Social Media**: Posts, stories, profile
      pictures - **App Assets**: Icons, splash screens, UI elements - **User Uploads**: Profile
      pictures, content submissions - **Large Galleries**: Photo albums, portfolios
  </Accordion>

  <Accordion title="❌ Skip Compression For">
    * **Print Materials**: Need maximum quality - **Professional Photography**: Client deliverables
    * **Medical/Scientific**: Requires perfect accuracy - **Already Optimized**: Files that are
      already small - **Videos**: Use dedicated video encoders instead
  </Accordion>
</AccordionGroup>

## Storage Savings Calculator

### Per-Image Savings

```
1 image at 80% compression:
├─ Original: 2.5 MB
├─ Compressed: 1.0 MB
└─ Saved: 1.5 MB (60%)

100 images:
└─ Saved: 150 MB

1,000 images:
└─ Saved: 1.5 GB

10,000 images:
└─ Saved: 15 GB ✨
```

### Cost Savings

With Imperial's pricing:

```
Starter Plan (5 GB):
├─ Without compression: ~2,000 images
└─ With compression: ~5,000 images (2.5x more!)

Pro Plan (10 GB):
├─ Without compression: ~4,000 images
└─ With compression: ~10,000 images
```

<Tip>Compression effectively **2-3x your storage capacity** without any extra cost!</Tip>

## Performance Impact

### Upload Processing Time

Compression adds minimal overhead:

| Image Size | Without Compression | With Compression | Overhead |
| ---------- | ------------------- | ---------------- | -------- |
| 1 MB       | 200ms               | 250ms            | +50ms    |
| 5 MB       | 800ms               | 950ms            | +150ms   |
| 10 MB      | 1,500ms             | 1,800ms          | +300ms   |

<Info>
  The slight processing delay is offset by faster uploads to R2 (smaller files) and faster CDN
  delivery to users.
</Info>

## Configuration

Enable compression in your dashboard:

<Steps>
  <Step title="Navigate to Settings">
    Go to [Dashboard Settings](https://app.imperial.gay/settings) → Uploads
  </Step>

  <Step title="Enable Auto-Compress">Toggle "Auto-compress images" on</Step>
  <Step title="Set Quality">Choose your quality level (60-100%) **Recommended: 80%**</Step>
  <Step title="Save Changes">Your preference applies to all future uploads</Step>
</Steps>

### API Usage

Compression settings are account-level and apply automatically to API uploads:

```bash theme={null}
# Uploads automatically compressed based on your settings
curl -X POST https://api.imperial.gay/images/upload \
  -H "Authorization: Bearer imperial_live_xxxxxxxxxxxxx" \
  -F "file=@photo.jpg"

# Response includes compression info
{
  "compressed": true,
  "originalSize": 2500000,
  "compressedSize": 1000000
}
```

## Quality Comparison

### Visual Examples

<Tabs>
  <Tab title="100% Quality">
    * **File Size**: 2.4 MB - **Quality**: Perfect, original - **Use Case**: Archival, print
  </Tab>

  <Tab title="90% Quality">
    * **File Size**: 1.8 MB (25% smaller) - **Quality**: Nearly perfect - **Use Case**: Professional
      web
  </Tab>

  <Tab title="80% Quality ⭐">
    * **File Size**: 1.0 MB (58% smaller) - **Quality**: Excellent - **Use Case**: General web use
      (recommended)
  </Tab>

  <Tab title="70% Quality">
    * **File Size**: 720 KB (70% smaller) - **Quality**: Good - **Use Case**: Thumbnails, previews
  </Tab>

  <Tab title="60% Quality">
    * **File Size**: 580 KB (76% smaller) - **Quality**: Acceptable - **Use Case**: Low-bandwidth
      scenarios
  </Tab>
</Tabs>

## Advanced Features

### Progressive JPEG

All compressed JPEGs use progressive encoding:

```
Baseline JPEG:
└─ Loads top-to-bottom
└─ Slow on poor connections

Progressive JPEG:
├─ Loads in increasing quality
├─ Shows full image immediately (low quality)
└─ Refines to full quality
└─ Better perceived performance
```

### Metadata Preservation

Imperial preserves important metadata:

* **EXIF**: Camera info, date taken (optional)
* **Color Profile**: sRGB, Display P3
* **Orientation**: Proper rotation

But strips:

* **GPS Data**: For privacy
* **Thumbnail**: Redundant, increases size

## Disable Compression

Need original quality? Simply disable compression in settings:

<Warning>
  Disabling compression means: - Files are stored at original size - Uses more of your storage quota

  * May load slower for end users - Costs remain the same per GB
</Warning>

## Get Started

Try compression and see the savings:

<Card title="Upload and Compare" icon="rocket" href="/quickstart">
  Upload an image to see compression in action
</Card>
