Skip to content

Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.

feat: add gemini-image-gen and image-processing skills (#43, #44)

Jeremy Dawesd91773f65531
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index 5a17e756..21465313 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -27,7 +27,7 @@
},
{
"name": "design-assets",
- "description": "Generate colour palettes, favicon packages, and custom SVG icon sets from brand colours.",
+ "description": "Generate colour palettes, favicon packages, custom SVG icon sets, AI-generated images (Gemini), and image processing (resize, convert, optimise).",
"source": "./plugins/design-assets",
"category": "design"
},
diff --git a/CLAUDE.md b/CLAUDE.md
index 56d7d0bc..48e82fd9 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -15,7 +15,7 @@ Production workflow skills for Claude Code CLI. Each skill guides Claude through
```
claude-skills/
-├── plugins/ # 9 installable plugins (32 skills)
+├── plugins/ # 9 installable plugins (34 skills)
│ ├── cloudflare/ # Cloudflare Workers, Hono, D1/Drizzle, Vite, TanStack Start
│ │ └── skills/
│ │ ├── cloudflare-worker-builder/
@@ -32,11 +32,13 @@ claude-skills/
│ │ └── skills/
│ │ ├── tailwind-theme-builder/
│ │ └── shadcn-ui/
-│ ├── design-assets/ # Colour palettes, favicons, icons
+│ ├── design-assets/ # Colour palettes, favicons, icons, image gen/processing
│ │ └── skills/
│ │ ├── color-palette/
│ │ ├── favicon-gen/
-│ │ └── icon-set-generator/
+│ │ ├── icon-set-generator/
+│ │ ├── gemini-image-gen/
+│ │ └── image-processing/
│ ├── integrations/ # Google, ElevenLabs, MCP
│ │ └── skills/
│ │ ├── google-chat-messages/
diff --git a/README.md b/README.md
index 20a38ede..107e5986 100644
--- a/README.md
+++ b/README.md
@@ -11,9 +11,9 @@ Workflow skills for [Claude Code](https://claude.com/claude-code) that produce t
| **cloudflare** | cloudflare-worker-builder, vite-flare-starter, tanstack-start, hono-api-scaffolder, d1-drizzle-schema | Deployable Cloudflare Workers, full-stack apps, TanStack Start SSR dashboards, Hono APIs, D1 schemas |
| **web-design** | web-design-methodology, web-design-patterns, seo-local-business | Production HTML/CSS, component patterns, local business SEO |
| **frontend** | tailwind-theme-builder, shadcn-ui | Themed Tailwind v4 + shadcn/ui setup with dark mode |
-| **design-assets** | color-palette, favicon-gen, icon-set-generator | Colour palettes, favicon packages, custom SVG icon sets |
+| **design-assets** | color-palette, favicon-gen, icon-set-generator, gemini-image-gen, image-processing | Colour palettes, favicons, SVG icons, AI image generation, image processing |
| **integrations** | google-chat-messages, google-apps-script, elevenlabs-agents, mcp-builder | Google Chat webhooks, Apps Script, ElevenLabs agents, MCP servers |
-| **dev-tools** | skill-creator, project-kickoff, context-manager, dev-session, github-release, gemini-peer-review, gemini-guide, claude-capabilities, ux-audit, responsiveness-check | Skill creation, project bootstrapping, context audits, session tracking, releases, Gemini peer review and API guide, UX audits, responsive layout testing |
+| **dev-tools** | skill-creator, project-health, dev-session, github-release, gemini-peer-review, gemini-guide, claude-capabilities, ux-audit, responsiveness-check | Skill creation, project health audits, session tracking, releases, Gemini peer review, API guide, UX audits, responsive testing |
| **shopify** | shopify-setup, shopify-products, shopify-content | Shopify API setup, product management, content pages, blog posts |
| **wordpress** | wordpress-setup, wordpress-content, wordpress-elementor | WordPress WP-CLI access, content management, Elementor page editing |
| **writing** | aussie-business-english | Australian business English writing style |
diff --git a/plugins/design-assets/.claude-plugin/plugin.json b/plugins/design-assets/.claude-plugin/plugin.json
index d7ca1be6..4e8d1998 100644
--- a/plugins/design-assets/.claude-plugin/plugin.json
+++ b/plugins/design-assets/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "design-assets",
- "description": "Generate colour palettes, favicon packages, and custom SVG icon sets from brand colours.",
+ "description": "Generate colour palettes, favicon packages, custom SVG icon sets, AI-generated images (Gemini), and image processing (resize, convert, optimise).",
"author": {
"name": "Jeremy Dawes / Jezweb",
"email": "[email protected]"
diff --git a/plugins/design-assets/skills/gemini-image-gen/SKILL.md b/plugins/design-assets/skills/gemini-image-gen/SKILL.md
new file mode 100644
index 00000000..597c9131
--- /dev/null
+++ b/plugins/design-assets/skills/gemini-image-gen/SKILL.md
@@ -0,0 +1,106 @@
+---
+name: gemini-image-gen
+description: "Generate images using Google's Gemini API — hero backgrounds, OG images, placeholder photos, textures, and style-matched variants. Uses free-tier models for drafts, paid for finals. No dependencies beyond Python 3. Trigger with 'generate image', 'gemini image', 'make a hero background', 'create placeholder photo', 'generate OG image', 'AI image', or 'need an image for'."
+compatibility: claude-code-only
+---
+
+# Gemini Image Generator
+
+Generate contextual images for web projects using the Gemini API. Produces hero backgrounds, OG cards, placeholder photos, textures, and style-matched variants.
+
+## Setup
+
+**API Key**: Retrieve from Vault and export:
+
+```
+mcp__vault__secret_get name="Google Gemini" folder="ai-services"
+export GEMINI_API_KEY="<key>"
+```
+
+## Workflow
+
+### Step 1: Understand What's Needed
+
+Gather from the user or project context:
+- **What**: hero background, product photo, texture, OG image, placeholder
+- **Style**: warm/cool/minimal/luxurious/bold — check project's colour palette (input.css, tailwind config)
+- **Dimensions**: hero (1920x1080), OG (1200x630), square (1024x1024), custom
+- **Count**: single image or multiple variants to choose from
+
+### Step 2: Build the Prompt
+
+Use concrete photography parameters, not abstract adjectives. Read [references/prompting-guide.md](references/prompting-guide.md) for the full framework.
+
+**Quick rules**:
+- Narrate like directing a photographer
+- Use camera specs: "85mm f/1.8", "wide angle 24mm"
+- Use colour anchors from the project palette: "warm terracotta (#C66A52) and cream (#F5F0EB) tones"
+- Use lighting descriptions: "golden-hour light from the left, 4500K"
+- Always end with: "No text, no watermarks, no logos, no hands"
+
+### Step 3: Generate
+
+```bash
+python3 plugins/design-assets/skills/gemini-image-gen/scripts/generate-image.py \
+ --prompt "Soft-focus atmospheric background, warm gold and cream botanical elements, luxury spa aesthetic, wide landscape" \
+ --output public/images/hero.png \
+ --model gemini-2.5-flash-image
+```
+
+Multiple variants:
+
+```bash
+python3 .../generate-image.py --prompt "..." --output public/images/hero.png --count 3
+# Produces hero-1.png, hero-2.png, hero-3.png
+```
+
+Style matching from a reference image:
+
+```bash
+python3 .../generate-image.py \
+ --prompt "Same warm lighting and colour palette, but showing a massage treatment room" \
+ --reference public/images/existing-hero.jpg \
+ --output public/images/services-bg.png \
+ --model gemini-3-pro-image-preview
+```
+
+### Step 4: Post-Process (Optional)
+
+Use the **image-processing** skill for resizing, format conversion, or optimisation:
+
+```bash
+python3 plugins/design-assets/skills/image-processing/scripts/process-image.py \
+ optimise public/images/hero.png --output public/images/hero.webp --width 1920
+```
+
+### Step 5: Present to User
+
+Show the generated images for review. Read the image files to display them inline if possible, otherwise describe what was generated and let the user open them.
+
+## Presets
+
+Starting prompts — enhance with project-specific context (colours, mood, subject):
+
+| Preset | Base Prompt |
+|--------|-------------|
+| `hero-background` | "Wide atmospheric background, soft-focus, [colour tones], [mood], landscape 1920x1080" |
+| `og-image` | "Clean branded card background, [brand colours], subtle gradient, 1200x630" |
+| `placeholder-photo` | "Professional stock-style photo of [subject], natural lighting, warm tones" |
+| `texture-pattern` | "Subtle repeating texture, [material], seamless tile, muted [colour]" |
+| `product-shot` | "Product photography, [item] on [surface], soft studio lighting, clean background" |
+
+## Model Selection
+
+| Use case | Model | Cost |
+|----------|-------|------|
+| Drafts, quick placeholders | `gemini-2.5-flash-image` | Free (~500/day) |
+| Final client assets | `gemini-3-pro-image-preview` | ~$0.04/image |
+| Style-matched variants | `gemini-3-pro-image-preview` + `--reference` | ~$0.04/image |
+
+Verify current model IDs if errors occur — they change frequently.
+
+## Reference Files
+
+| When | Read |
+|------|------|
+| Building effective prompts | [references/prompting-guide.md](references/prompting-guide.md) |
diff --git a/plugins/design-assets/skills/gemini-image-gen/references/prompting-guide.md b/plugins/design-assets/skills/gemini-image-gen/references/prompting-guide.md
new file mode 100644
index 00000000..4e4fd492
--- /dev/null
+++ b/plugins/design-assets/skills/gemini-image-gen/references/prompting-guide.md
@@ -0,0 +1,114 @@
+# Gemini Image Prompting Guide
+
+## The 5-Part Prompt Framework
+
+Build prompts using these five components in order:
+
+### 1. Scene Setup
+What's in the image — subject, setting, composition.
+
+```
+"A woman receiving a facial treatment in a luxury day spa"
+"A modern office workspace with plants and warm lighting"
+"An aerial view of a coastal town at sunset"
+```
+
+### 2. Camera & Lens
+Concrete photography parameters control the look more reliably than adjectives.
+
+| Parameter | Effect | Example |
+|-----------|--------|---------|
+| Focal length | Compression/perspective | "85mm" (portrait), "24mm" (wide), "135mm" (compressed) |
+| Aperture | Depth of field | "f/1.8" (blurry bg), "f/8" (sharp throughout) |
+| Angle | Perspective | "eye level", "overhead flat lay", "low angle looking up" |
+| Distance | Framing | "close-up", "medium shot", "wide establishing shot" |
+
+```
+"Shot at 85mm f/1.8, shallow depth of field, medium shot from eye level"
+```
+
+### 3. Lighting
+Describe the light source, quality, and colour temperature.
+
+| Instead of... | Use... |
+|---------------|--------|
+| "beautiful lighting" | "warm golden-hour light from the left, 4500K" |
+| "professional lighting" | "soft diffused window light, slight rim light from behind" |
+| "moody lighting" | "low-key dramatic side lighting, deep shadows, single source" |
+
+```
+"Warm directional light from a large window on the right, soft shadows, 4000K colour temperature"
+```
+
+### 4. Colour Palette
+Anchor to specific colours from the project. Use hex codes or descriptive anchors.
+
+```
+"Warm terracotta (#C66A52) and cream (#F5F0EB) tones throughout"
+"Cool slate blue and white palette, desaturated"
+"Rich emerald green and gold accents"
+```
+
+**Pull from the project**: check `input.css`, `tailwind.config`, or the colour-palette skill output for exact values.
+
+### 5. Negative Constraints
+What to exclude. Always include these:
+
+```
+"No text, no watermarks, no logos, no hands, no fingers"
+```
+
+Add context-specific negatives:
+
+```
+"No people" (for abstract backgrounds)
+"No artificial elements" (for nature shots)
+"No cluttered background" (for product shots)
+```
+
+## Complete Example
+
+```
+A woman receiving a gentle facial treatment in a luxury day spa,
+warm golden-hour light streaming through sheer curtains from the left,
+shot at 85mm f/2.0 with shallow depth of field,
+warm terracotta and cream colour palette,
+soft bokeh in the background showing spa interior,
+photorealistic, natural skin texture,
+no text, no watermarks, no logos, no hands visible
+```
+
+## Style Matching with Reference Images
+
+When using `--reference` to match an existing image's style:
+
+1. **Be specific about what to change** (subject, framing, setting)
+2. **Let the model infer what to keep** (lighting, colour palette, mood)
+3. **Lower temperature** (0.7) stays closer to the reference
+
+```
+"Using the same warm lighting, colour palette, and photographic style as the reference image,
+generate a close-up of hands performing a massage treatment on a spa table.
+Maintain the same soft-focus background treatment and golden tones."
+```
+
+## Common Failure Modes
+
+| Issue | Fix |
+|-------|-----|
+| Text appears in image | Add "no text, no words, no letters" explicitly |
+| Hands look wrong | Add "no hands, no fingers" or crop hands out |
+| Too generic/stock-photo | Add specific camera specs and colour anchors |
+| Inconsistent style across variants | Use `--reference` with the best variant as input |
+| Image has watermark-like patterns | Add "clean image, no watermarks, no artifacts" |
+
+## Web Asset Dimensions
+
+| Use case | Dimensions | Aspect Ratio |
+|----------|-----------|--------------|
+| Hero banner | 1920x1080 | 16:9 |
+| OG / social card | 1200x630 | ~1.9:1 |
+| Square thumbnail | 1024x1024 | 1:1 |
+| Blog header | 1200x675 | 16:9 |
+| Product photo | 1024x1024 | 1:1 |
+| Texture/pattern tile | 512x512 | 1:1 |
diff --git a/plugins/design-assets/skills/gemini-image-gen/scripts/generate-image.py b/plugins/design-assets/skills/gemini-image-gen/scripts/generate-image.py
new file mode 100644
index 00000000..37d73e0b
--- /dev/null
+++ b/plugins/design-assets/skills/gemini-image-gen/scripts/generate-image.py
@@ -0,0 +1,111 @@
+#!/usr/bin/env python3
+"""Generate images via Gemini API. No dependencies beyond Python 3 stdlib.
+
+Usage:
+ # Text-to-image
+ python3 generate-image.py --prompt "A warm hero background for a spa website" --output hero.png
+
+ # With style reference image
+ python3 generate-image.py --prompt "Same style, different subject" --reference ref.jpg --output out.png
+
+ # Multiple variants
+ python3 generate-image.py --prompt "..." --output variant.png --count 3
+
+ # Use pro model for final assets
+ python3 generate-image.py --prompt "..." --output final.png --model gemini-3-pro-image-preview
+
+Reads GEMINI_API_KEY from environment.
+"""
+
+import argparse
+import base64
+import json
+import os
+import sys
+import urllib.request
+import urllib.error
+
+
+def generate(model: str, prompt: str, api_key: str, reference_path: str = None) -> bytes:
+ url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={api_key}"
+
+ parts = []
+
+ if reference_path:
+ with open(reference_path, "rb") as f:
+ img_data = base64.b64encode(f.read()).decode()
+ ext = reference_path.rsplit(".", 1)[-1].lower()
+ mime = {"jpg": "image/jpeg", "jpeg": "image/jpeg", "png": "image/png", "webp": "image/webp"}.get(ext, "image/jpeg")
+ parts.append({"inlineData": {"mimeType": mime, "data": img_data}})
+
+ parts.append({"text": prompt})
+
+ payload = json.dumps({
+ "contents": [{"parts": parts}],
+ "generationConfig": {
+ "responseModalities": ["TEXT", "IMAGE"],
+ "temperature": 0.7 if reference_path else 1.0,
+ },
+ }).encode()
+
+ req = urllib.request.Request(url, data=payload, headers={"Content-Type": "application/json"}, method="POST")
+
+ try:
+ with urllib.request.urlopen(req, timeout=120) as resp:
+ data = json.loads(resp.read().decode())
+ except urllib.error.HTTPError as e:
+ body = e.read().decode() if e.fp else ""
+ print(f"Gemini API error {e.code}: {body}", file=sys.stderr)
+ sys.exit(1)
+
+ # Extract image from response
+ try:
+ for candidate in data.get("candidates", []):
+ for part in candidate.get("content", {}).get("parts", []):
+ if "inlineData" in part:
+ return base64.b64decode(part["inlineData"]["data"])
+ except (KeyError, IndexError):
+ pass
+
+ # No image in response — print text response for debugging
+ try:
+ text = data["candidates"][0]["content"]["parts"][0].get("text", "")
+ if text:
+ print(f"Gemini returned text instead of image: {text}", file=sys.stderr)
+ except (KeyError, IndexError):
+ print(f"Unexpected response: {json.dumps(data, indent=2)[:500]}", file=sys.stderr)
+ sys.exit(1)
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Generate images via Gemini API")
+ parser.add_argument("--prompt", required=True, help="Image generation prompt")
+ parser.add_argument("--output", required=True, help="Output file path (e.g. hero.png)")
+ parser.add_argument("--model", default="gemini-2.5-flash-image", help="Gemini model ID")
+ parser.add_argument("--reference", help="Reference image for style matching")
+ parser.add_argument("--count", type=int, default=1, help="Number of variants to generate")
+ args = parser.parse_args()
+
+ api_key = os.environ.get("GEMINI_API_KEY")
+ if not api_key:
+ print("GEMINI_API_KEY not set. Get from Vault: mcp__vault__secret_get name='Google Gemini' folder='ai-services'", file=sys.stderr)
+ sys.exit(1)
+
+ for i in range(args.count):
+ if args.count > 1:
+ base, ext = args.output.rsplit(".", 1)
+ output_path = f"{base}-{i+1}.{ext}"
+ else:
+ output_path = args.output
+
+ print(f"Generating {output_path}...", file=sys.stderr)
+ img_bytes = generate(args.model, args.prompt, api_key, args.reference)
+
+ os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)
+ with open(output_path, "wb") as f:
+ f.write(img_bytes)
+ print(f"Saved {output_path} ({len(img_bytes):,} bytes)", file=sys.stderr)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/plugins/design-assets/skills/image-processing/SKILL.md b/plugins/design-assets/skills/image-processing/SKILL.md
new file mode 100644
index 00000000..5389f3f2
--- /dev/null
+++ b/plugins/design-assets/skills/image-processing/SKILL.md
@@ -0,0 +1,144 @@
+---
+name: image-processing
+description: "Process images for web development — resize, crop, trim whitespace, convert formats (PNG/WebP/JPG), optimise file size, generate thumbnails, create OG card images. Uses Pillow (Python) — no ImageMagick needed. Trigger with 'resize image', 'convert to webp', 'trim logo', 'optimise images', 'make thumbnail', 'create OG image', 'crop whitespace', 'process image', or 'image too large'."
+compatibility: claude-code-only
+---
+
+# Image Processing
+
+Process images for web development using Pillow (Python). Resize, convert, trim, optimise, and composite — no ImageMagick or native dependencies required.
+
+## Prerequisites
+
+Pillow is usually pre-installed. If not:
+
+```bash
+pip install Pillow
+```
+
+## Commands
+
+All commands use `scripts/process-image.py`. Each takes `--output` (`-o`) and optional `--quality` (`-q`).
+
+### Resize
+
+Scale an image to specific dimensions or by width/height (maintains aspect ratio if only one given).
+
+```bash
+python3 plugins/design-assets/skills/image-processing/scripts/process-image.py \
+ resize input.png -o resized.png --width 1920 --height 1080
+
+# Width only — height calculated from aspect ratio
+python3 .../process-image.py resize input.png -o resized.png -w 800
+```
+
+### Convert Format
+
+Convert between PNG, JPG, WebP. RGBA→JPG automatically composites onto white background.
+
+```bash
+python3 .../process-image.py convert logo.png -o logo.webp
+python3 .../process-image.py convert photo.webp -o photo.jpg -q 90
+```
+
+### Trim Whitespace
+
+Auto-crop surrounding whitespace from logos and icons.
+
+```bash
+python3 .../process-image.py trim logo-with-padding.png -o logo-trimmed.png
+```
+
+### Thumbnail
+
+Create a thumbnail fitting within a max dimension (maintains aspect ratio).
+
+```bash
+python3 .../process-image.py thumbnail product.jpg -o thumb.jpg --size 300
+```
+
+### Optimise for Web
+
+Resize + compress in one step. Ideal for preparing uploaded images for production.
+
+```bash
+python3 .../process-image.py optimise hero.jpg -o hero.webp -w 1920 -q 85
+```
+
+### OG Card
+
+Generate a 1200x630 Open Graph card image with title and subtitle overlay.
+
+```bash
+# With background image
+python3 .../process-image.py og-card \
+ --background hero.jpg \
+ --title "My Page Title" \
+ --subtitle "A brief description" \
+ -o og-image.png
+
+# Solid colour background
+python3 .../process-image.py og-card \
+ --bg-color "#1a1a2e" \
+ --title "My Page Title" \
+ -o og-image.png
+```
+
+## Common Workflows
+
+### Logo Cleanup (client-supplied JPG with white background)
+
+```bash
+# 1. Trim whitespace
+python3 .../process-image.py trim client-logo.jpg -o logo-trimmed.png
+
+# 2. Convert to PNG (for transparency on non-white backgrounds)
+python3 .../process-image.py convert logo-trimmed.png -o logo.png
+
+# 3. Create favicon-sized version
+python3 .../process-image.py thumbnail logo.png -o favicon-source.png --size 512
+```
+
+### Prepare Hero Image for Production
+
+```bash
+# Resize to max width, convert to WebP, compress
+python3 .../process-image.py optimise uploaded-hero.jpg -o public/images/hero.webp -w 1920 -q 85
+```
+
+### Batch Process (Multiple Images)
+
+For batch operations, write a quick script rather than running commands one by one:
+
+```python
+import subprocess, glob
+for img in glob.glob("uploads/*.jpg"):
+ name = img.rsplit("/", 1)[-1].replace(".jpg", ".webp")
+ subprocess.run(["python3", ".../process-image.py", "optimise", img, "-o", f"public/images/{name}", "-w", "1200", "-q", "85"])
+```
+
+## Pipeline with Gemini Image Gen
+
+Generate → Process → Deploy:
+
+```bash
+# 1. Generate with Gemini
+python3 plugins/design-assets/skills/gemini-image-gen/scripts/generate-image.py \
+ --prompt "..." --output raw-hero.png --count 3
+
+# 2. User picks favourite (e.g. raw-hero-2.png)
+
+# 3. Optimise for web
+python3 plugins/design-assets/skills/image-processing/scripts/process-image.py \
+ optimise raw-hero-2.png -o public/images/hero.webp -w 1920 -q 85
+```
+
+## Output Format Guide
+
+| Use case | Format | Why |
+|----------|--------|-----|
+| Photos, hero images | WebP | Best compression, wide browser support |
+| Logos, icons (need transparency) | PNG | Lossless, supports alpha |
+| Fallback for older browsers | JPG | Universal support |
+| Thumbnails | WebP or JPG | Small file size priority |
+| OG cards | PNG | Social platforms handle PNG best |
diff --git a/plugins/design-assets/skills/image-processing/scripts/process-image.py b/plugins/design-assets/skills/image-processing/scripts/process-image.py
new file mode 100644
index 00000000..1360236b
--- /dev/null
+++ b/plugins/design-assets/skills/image-processing/scripts/process-image.py
@@ -0,0 +1,212 @@
+#!/usr/bin/env python3
+"""Image processing with Pillow. Handles common web dev image tasks.
+
+Usage:
+ # Resize
+ python3 process-image.py resize input.png --output resized.png --width 1920 --height 1080
+
+ # Convert format (PNG→WebP, JPG→PNG with transparency, etc.)
+ python3 process-image.py convert input.png --output output.webp
+
+ # Trim whitespace (auto-crop)
+ python3 process-image.py trim logo.png --output trimmed.png
+
+ # Create thumbnail
+ python3 process-image.py thumbnail input.jpg --output thumb.jpg --size 300
+
+ # Optimise for web (resize + WebP + quality)
+ python3 process-image.py optimise input.jpg --output optimised.webp --width 1200 --quality 85
+
+ # Composite text on image (for OG cards)
+ python3 process-image.py og-card --background bg.png --output og.png --title "Page Title" --subtitle "Description"
+
+Requires: pip install Pillow (usually pre-installed)
+"""
+
+import argparse
+import os
+import sys
+
+try:
+ from PIL import Image, ImageDraw, ImageFont, ImageFilter
+except ImportError:
+ print("Pillow not installed. Run: pip install Pillow", file=sys.stderr)
+ sys.exit(1)
+
+
+def cmd_resize(args):
+ img = Image.open(args.input)
+ if args.width and args.height:
+ img = img.resize((args.width, args.height), Image.LANCZOS)
+ elif args.width:
+ ratio = args.width / img.width
+ img = img.resize((args.width, int(img.height * ratio)), Image.LANCZOS)
+ elif args.height:
+ ratio = args.height / img.height
+ img = img.resize((int(img.width * ratio), args.height), Image.LANCZOS)
+ save_image(img, args.output, args.quality)
+
+
+def cmd_convert(args):
+ img = Image.open(args.input)
+ if args.output.lower().endswith((".jpg", ".jpeg")) and img.mode == "RGBA":
+ bg = Image.new("RGB", img.size, (255, 255, 255))
+ bg.paste(img, mask=img.split()[3])
+ img = bg
+ save_image(img, args.output, args.quality)
+
+
+def cmd_trim(args):
+ img = Image.open(args.input)
+ if img.mode != "RGBA":
+ img = img.convert("RGBA")
+ # Use alpha channel or detect background colour from corners
+ bbox = img.getbbox()
+ if bbox:
+ img = img.crop(bbox)
+ save_image(img, args.output, args.quality)
+
+
+def cmd_thumbnail(args):
+ img = Image.open(args.input)
+ size = args.size or 300
+ img.thumbnail((size, size), Image.LANCZOS)
+ save_image(img, args.output, args.quality)
+
+
+def cmd_optimise(args):
+ img = Image.open(args.input)
+ if args.width:
+ ratio = args.width / img.width
+ img = img.resize((args.width, int(img.height * ratio)), Image.LANCZOS)
+ save_image(img, args.output, args.quality or 85)
+
+
+def cmd_og_card(args):
+ width, height = 1200, 630
+ if args.background:
+ img = Image.open(args.background).resize((width, height), Image.LANCZOS)
+ else:
+ img = Image.new("RGB", (width, height), args.bg_color or "#1a1a2e")
+
+ # Semi-transparent overlay for text readability
+ overlay = Image.new("RGBA", (width, height), (0, 0, 0, 128))
+ img = img.convert("RGBA")
+ img = Image.alpha_composite(img, overlay)
+
+ draw = ImageDraw.Draw(img)
+
+ # Try to find a good font, fall back to default
+ font_title = _get_font(48)
+ font_sub = _get_font(24)
+
+ # Title
+ if args.title:
+ bbox = draw.textbbox((0, 0), args.title, font=font_title)
+ tw = bbox[2] - bbox[0]
+ x = (width - tw) // 2
+ draw.text((x, height // 2 - 60), args.title, fill="white", font=font_title)
+
+ # Subtitle
+ if args.subtitle:
+ bbox = draw.textbbox((0, 0), args.subtitle, font=font_sub)
+ tw = bbox[2] - bbox[0]
+ x = (width - tw) // 2
+ draw.text((x, height // 2 + 20), args.subtitle, fill="#cccccc", font=font_sub)
+
+ img = img.convert("RGB")
+ save_image(img, args.output, args.quality)
+
+
+def _get_font(size):
+ """Try system fonts, fall back to Pillow default."""
+ font_paths = [
+ "/System/Library/Fonts/Helvetica.ttc",
+ "/System/Library/Fonts/SFNSText.ttf",
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
+ ]
+ for path in font_paths:
+ if os.path.exists(path):
+ try:
+ return ImageFont.truetype(path, size)
+ except Exception:
+ continue
+ return ImageFont.load_default()
+
+
+def save_image(img, output, quality=None):
+ os.makedirs(os.path.dirname(output) or ".", exist_ok=True)
+ kwargs = {}
+ ext = output.lower().rsplit(".", 1)[-1]
+ if ext == "webp":
+ kwargs = {"quality": quality or 85, "method": 6}
+ elif ext in ("jpg", "jpeg"):
+ kwargs = {"quality": quality or 90, "optimize": True}
+ if img.mode == "RGBA":
+ bg = Image.new("RGB", img.size, (255, 255, 255))
+ bg.paste(img, mask=img.split()[3])
+ img = bg
+ elif ext == "png":
+ kwargs = {"optimize": True}
+
+ img.save(output, **kwargs)
+ size = os.path.getsize(output)
+ print(f"Saved {output} ({img.width}x{img.height}, {size:,} bytes)")
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Image processing for web development")
+ sub = parser.add_subparsers(dest="command", required=True)
+
+ # Shared args
+ def add_common(p):
+ p.add_argument("--output", "-o", required=True, help="Output file path")
+ p.add_argument("--quality", "-q", type=int, help="Output quality (1-100)")
+
+ # resize
+ p = sub.add_parser("resize", help="Resize image")
+ p.add_argument("input", help="Input file")
+ p.add_argument("--width", "-w", type=int)
+ p.add_argument("--height", type=int)
+ add_common(p)
+
+ # convert
+ p = sub.add_parser("convert", help="Convert format")
+ p.add_argument("input", help="Input file")
+ add_common(p)
+
+ # trim
+ p = sub.add_parser("trim", help="Auto-crop whitespace")
+ p.add_argument("input", help="Input file")
+ add_common(p)
+
+ # thumbnail
+ p = sub.add_parser("thumbnail", help="Create thumbnail")
+ p.add_argument("input", help="Input file")
+ p.add_argument("--size", "-s", type=int, default=300, help="Max dimension")
+ add_common(p)
+
+ # optimise
+ p = sub.add_parser("optimise", help="Optimise for web")
+ p.add_argument("input", help="Input file")
+ p.add_argument("--width", "-w", type=int, help="Max width (maintains aspect)")
+ add_common(p)
+
+ # og-card
+ p = sub.add_parser("og-card", help="Generate OG card image")
+ p.add_argument("--background", help="Background image (optional)")
+ p.add_argument("--bg-color", default="#1a1a2e", help="Background colour if no image")
+ p.add_argument("--title", required=True, help="Card title")
+ p.add_argument("--subtitle", help="Card subtitle")
+ add_common(p)
+
+ args = parser.parse_args()
+ commands = {
+ "resize": cmd_resize, "convert": cmd_convert, "trim": cmd_trim,
+ "thumbnail": cmd_thumbnail, "optimise": cmd_optimise, "og-card": cmd_og_card,
+ }
+ commands[args.command](args)
+
+
+if __name__ == "__main__":
+ main()