← back to Resize It

SKILL.md

277 lines

---
name: resize-it
description: Resize images to 24" width at 150 DPI while maintaining aspect ratio. Analyzes quality degradation from scaling and uses AI vision (Claude/Gemini) to detect proportion distortions. Includes Spoonflower design download automation with authentication. Use when users need to resize images to specific print dimensions with quality and proportion verification, or when downloading designs from Spoonflower.
---

# Resize It

## Overview

This skill resizes images to print-ready dimensions (24" width at 150 DPI) while maintaining aspect ratio and analyzing the result for quality degradation and proportion distortion. It combines deterministic image processing with AI-powered visual analysis to ensure users understand the impact of resizing operations. For Spoonflower designs, it includes automated download capabilities with authentication support.

## Workflow

Follow this workflow when a user requests image resizing:

### 0. Download from Spoonflower (if applicable)

**IMPORTANT URL REQUIREMENTS:**

The user MUST provide a REAL, WORKING design page URL copied from their browser's address bar. Do NOT try to guess URL patterns from just a numeric ID.

**Accept these canonical design URLs:**
- `https://www.spoonflower.com/en/design/12345678-design-name-here`
- `https://www.spoonflower.com/en/fabric/12345678-design-name-here`
- `https://www.spoonflower.com/en/wallpaper/12345678-design-name-here`

**REJECT these URLs (listing/artist pages, no File Options menu):**
- `https://www.spoonflower.com/artists/designs/12345678`
- `https://www.spoonflower.com/en/artists/wallpaper/12345678`

If the user provides a Spoonflower URL, use the download script to authenticate and download the highest resolution file:

```bash
python3 scripts/download_spoonflower.py <spoonflower_url> <email> <password>
```

**Parameters:**
- `spoonflower_url`: Full canonical URL to the Spoonflower design page (must include `/en/` and design slug)
- `email`: Spoonflower account email
- `password`: Spoonflower account password

**How it works:**
1. Logs in to Spoonflower first
2. Navigates to the design page (must be owned by the logged-in account)
3. Locates and clicks "File Options" button
4. Downloads the highest resolution file available
5. Saves to /tmp/ directory

**Note:** Requires Playwright installation (`pip3 install playwright && python3 -m playwright install chromium`)

**If the URL doesn't work:**
- Ask the user to open their browser, log in to Spoonflower, navigate to the exact design where they see "File Options", and copy the full URL from the address bar.

### 1. Initial Resize with Quality Analysis

Execute the resize script to perform the image transformation:

```bash
python3 scripts/resize_image.py <input_image_path> [--output <output_path>] [--width 24] [--dpi 150] [--quality 95]
```

**Parameters:**
- `input_image_path`: Path to the source image (required)
- `--output`: Custom output path (optional, auto-generated if not provided)
- `--width`: Target width in inches (default: 24)
- `--dpi`: Resolution in dots per inch (default: 150)
- `--quality`: JPEG quality 1-100 (default: 95)

**Script Output:**
The script outputs detailed information including:
- Original and resized dimensions (pixels)
- Physical dimensions (inches)
- Scale factor
- Quality warnings if upscaling or significant downscaling detected

**Quality Warning Types:**
- **Upscaling Warning**: Image is being enlarged, which may cause pixelation and quality loss
- **Significant Downscaling Info**: Image is being reduced by more than 50%, some detail will be lost

### 2. AI-Powered Proportion Analysis

After resizing, use AI vision capabilities to analyze proportions:

#### Gemini 3.0 Vision API (MANDATORY - ONLY USE THIS)

Use Google Gemini 3.0 for fast, accurate image analysis:

```typescript
const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
if (!GEMINI_API_KEY) {
  throw new Error('Missing required environment variable: GEMINI_API_KEY');
}

async function analyzeWithGemini(imageBase64: string): Promise<any> {
  const response = await fetch(
    `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${GEMINI_API_KEY}`,
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        contents: [{
          parts: [
            { inlineData: { mimeType: 'image/jpeg', data: imageBase64 } },
            { text: `Analyze this image for proportion/distortion issues.
Return JSON: { "distorted": boolean, "type": "none|horizontal|vertical", "severity": "none|minor|severe", "notes": "..." }` }
          ]
        }],
        generationConfig: { temperature: 0.1, maxOutputTokens: 300 }
      })
    }
  );
  return response.json();
}
```

**Why Gemini 3.0 ONLY:**
- Faster response times
- Excellent at detecting subtle distortions
- Cost-effective for batch processing
- **MANDATORY** - Do NOT use Claude Vision

#### Legacy Script (For Data Prep Only)

The `analyze_proportions.py` script prepares image data and prompts for external AI API calls:

```bash
python3 scripts/analyze_proportions.py --original <original_path> --resized <resized_path> [--output-format json]
```

This generates structured data for API integration with external AI services.

### 3. Report Results to User

Combine findings from both the resize operation and proportion analysis:

**Report Template:**
```
✅ Image resized successfully!

**Dimensions:**
- Original: [width]x[height]px
- Resized: [width]x[height]px
- Physical: [width]" x [height]" @ 150 DPI
- Scale factor: [factor]x

**Quality Assessment:**
[Include any quality warnings from resize_image.py]

**Proportion Analysis:**
[Include AI vision analysis results]
- Distortion detected: [yes/no]
- Severity: [none/minor/moderate/severe]
- Observations: [list key findings]
- Recommendation: [action to take]

**Output file:** [path]
```

## Script Details

### download_spoonflower.py

Automated Spoonflower design downloader with authentication support using Playwright browser automation.

**Key Features:**
- Automated browser-based authentication
- Navigates to design page and signs in
- Clicks "File Options" menu button
- Downloads highest resolution file available
- Saves files to /tmp/ directory with original filename

**Dependencies:**
- Playwright: `pip3 install playwright`
- Chromium browser: `python3 -m playwright install chromium`

**Usage:**
```bash
python3 scripts/download_spoonflower.py "https://www.spoonflower.com/artists/designs/XXXXXX" "email@example.com" "password"
```

**Note:** This script is particularly useful for accessing high-resolution files that require authentication to download.

### resize_image.py

Main resizing script with built-in quality analysis.

**Key Features:**
- High-quality Lanczos resampling for best results
- Maintains aspect ratio automatically
- Embeds DPI metadata in output file
- Detects and warns about upscaling (>100% scale)
- Alerts for significant downscaling (>50% reduction)
- Supports JPEG and PNG formats with optimization
- Auto-generates descriptive output filenames
- Compatible with both old and new Pillow versions

**Technical Details:**
- Target dimensions: 24" × proportional height at 150 DPI = 3600px × calculated height
- Resampling: LANCZOS (high-quality algorithm for both up and down scaling)
- Output naming: `{original_name}_24x{height}in_150dpi.{ext}`

### analyze_proportions.py

Helper script for preparing proportion analysis data for AI vision APIs.

**Key Features:**
- Base64 encodes images for API transmission
- Generates structured analysis prompts
- Supports single image or before/after comparison
- Outputs JSON format for API integration

**Note:** For most use cases, direct visual analysis (Option A) using Claude's built-in vision capabilities is simpler and more efficient than using this script.

## Dependencies

### Required (for image resizing)

The resize script requires Pillow (PIL):

```bash
pip3 install Pillow
```

Verify installation:
```bash
python3 -c "from PIL import Image; print('Pillow installed successfully')"
```

### Optional (for Spoonflower downloads)

The Spoonflower download script requires Playwright:

```bash
pip3 install playwright
python3 -m playwright install chromium
```

Verify installation:
```bash
python3 -c "from playwright.sync_api import sync_playwright; print('Playwright installed successfully')"
```

## Example Usage

**User request:** "Resize this image to 24 inches for printing"

**Workflow:**
1. Run: `python3 scripts/resize_image.py /path/to/image.jpg`
2. Read both original and resized images
3. Analyze proportions using Claude's vision
4. Report complete findings to user

**User request:** "Will this image lose quality if I make it 24\" wide?"

**Workflow:**
1. Run resize script to get quality analysis
2. Review scale factor and warnings
3. Perform visual analysis if concerns detected
4. Provide clear recommendation based on findings

## Tips

- **Always check scale factor**: Values > 1.0 indicate upscaling (quality concern)
- **Upscaling > 20%**: Strong warning recommended, significant quality loss likely
- **Visual analysis**: Especially important when upscaling or when user expresses proportion concerns
- **Custom dimensions**: Script supports different widths and DPIs via parameters
- **Format preservation**: Script maintains original format (JPEG/PNG) unless output extension specifies otherwise
- **Quality parameter**: For JPEGs, adjust `--quality` (1-100) to balance file size vs quality

## Limitations

- Script requires Pillow library installation
- Optimal for images already near target resolution
- Significant upscaling cannot create detail that doesn't exist in the original
- AI proportion analysis accuracy depends on image content complexity
- Very small or very large images may require manual parameter adjustment