diff --git a/README.md b/README.md index 7d62e52..9789a32 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ npx create-cloudinary-next ## Requirements -- **Node.js** — use a [current LTS](https://nodejs.org/en/about/previous-releases) release. +- **Node.js 22** or later - A **Cloudinary account** - [Sign up for free](https://cld.media/nextregisterreadme) - Your cloud name is in your [dashboard](https://console.cloudinary.com/app/home/dashboard) diff --git a/cli.js b/cli.js index 8f34193..f386265 100755 --- a/cli.js +++ b/cli.js @@ -2,7 +2,7 @@ import { fileURLToPath } from 'url'; import { dirname, join } from 'path'; -import { existsSync, mkdirSync, writeFileSync, readFileSync, cpSync, mkdtempSync, rmSync } from 'fs'; +import { existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync, cpSync, mkdtempSync, rmSync } from 'fs'; import { tmpdir } from 'os'; import { spawnSync } from 'child_process'; import { parseArgs } from 'node:util'; @@ -89,8 +89,15 @@ function readTemplate(relativePath) { } function findSkillSourceDir(baseDir, skillName) { - const candidates = [join(baseDir, 'skills', skillName), join(baseDir, skillName)]; - return candidates.find((candidate) => existsSync(candidate)); + const skillsDir = join(baseDir, 'skills'); + // The skills repo groups skills into category folders (skills//) + const categoryCandidates = existsSync(skillsDir) + ? readdirSync(skillsDir, { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .map((entry) => join(skillsDir, entry.name, skillName)) + : []; + const candidates = [join(skillsDir, skillName), ...categoryCandidates, join(baseDir, skillName)]; + return candidates.find((candidate) => existsSync(join(candidate, 'SKILL.md'))); } function writeFileEnsureDir(filePath, content) { @@ -166,6 +173,9 @@ function writeSkill(projectPath, aiTools) { } if (!sourceDir) { + if (remoteInstallAvailable) { + console.log(chalk.yellow(` ${skillName} not found in the Cloudinary skills repo; using the bundled local backup.`)); + } sourceDir = localFallbacks[skillName]; } diff --git a/package.json b/package.json index b1ecce9..c77d0e6 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,7 @@ "author": "Cloudinary, Inc.", "license": "MIT", "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" }, "scripts": { "semantic-release": "semantic-release" diff --git a/templates/skills/cloudinary-docs/SKILL.md b/templates/skills/cloudinary-docs/SKILL.md index 2aaf571..80f7a76 100644 --- a/templates/skills/cloudinary-docs/SKILL.md +++ b/templates/skills/cloudinary-docs/SKILL.md @@ -1,31 +1,88 @@ --- name: cloudinary-docs -description: look up the latest cloudinary docs and official references. use when answering cloudinary questions or implementing uploads, optimization, transformations, apis, webhooks, or integrations. +description: Looks up implementation details in the latest Cloudinary docs via the relevant llms.txt file. Use when building code or answering questions relating to image or video uploads, management, SDKs, APIs, webhooks, or integrations. For topics covered by a specialized Cloudinary skill, prefer that skill. Use this skill alongside it when the full use-case requires capabilities outside that skill's scope. +license: MIT +metadata: + author: cloudinary + version: '1.1.0' --- -# Cloudinary Docs +# Cloudinary Documentation -## Purpose +Helps developers integrate Cloudinary into their applications by providing documentation and code examples retrieved directly from the agent-optimized markdown files in the Cloudinary documentation. -Use this skill when you need current Cloudinary documentation instead of memory or stale examples. +## When to Use -## Core workflow +- When a user asks questions or requests code implementation relating to image or video upload, management, SDKs, APIs, webhooks, or integrations +- For topics covered by a more specialized Cloudinary skill (e.g. transformations, React SDK): prefer that skill. Use this skill alongside it when the full use-case also requires capabilities outside that skill's scope. +- General Cloudinary documentation lookup (account settings, webhooks, DAM features) +- Looking up specific Cloudinary API endpoints or SDK methods +- When a specialized Cloudinary skill handles part of a use-case, use this skill to cover the remaining capabilities it doesn't address, not as a substitute for it. -1. Identify the Cloudinary product area first. -2. Prefer the latest official docs and llms.txt over examples copied from old code. -3. Verify package names, environment variables, event names, and configuration shapes before coding. -4. When a detail is version-sensitive, check the official docs instead of guessing. +## Sub-file Index Overview -## Use it for +The main documentation llms.txt file is split into product-specific sub-files. **Go directly to the relevant sub-file** according to the descriptions below. Do not fetch the main llms.txt first unless the topic spans multiple products or you are unsure. -- Uploads and upload presets -- Delivery, optimization, and transformation questions -- SDK and API usage -- Webhooks and server-side workflows -- Troubleshooting and version-sensitive behavior +| Product | Topic | Sub-file URL | +|---|---|---| +| Image & Video APIs | Image/video uploads, transformations, optimization, SDKs, APIs, webhooks, add-ons, embedding widgets or players in apps, or any programmatic/automation/at-scale image and video requirements | https://cloudinary.com/documentation/llms-image-and-video-apis.txt?install_source=skillspack&referrer=docs-skill | +| Cloudinary Assets (DAM) | Digital Asset Management (DAM), Media Library, folders, metadata, collections, creative workflows, portals, digital rights, or any Cloudinary Console or UI-based asset management needs | https://cloudinary.com/documentation/llms-cloudinary-assets.txt?install_source=skillspack&referrer=docs-skill | +| MediaFlows | PowerFlows, EasyFlows, workflow automation, flow blocks | https://cloudinary.com/documentation/llms-mediaflows.txt?install_source=skillspack&referrer=docs-skill | +| Integrations | Cloudinary integrations with 3rd party apps (WordPress, Shopify, Contentful, Salesforce, Adobe, etc.) or questions about implementing new integrations | https://cloudinary.com/documentation/llms-integrations.txt?install_source=skillspack&referrer=docs-skill | +| Cross-product or unsure | Multiple products, general, or unclear topic | https://cloudinary.com/documentation/llms.txt?install_source=skillspack&referrer=docs-skill | -## Rules +## Instructions -- Do not invent API names or prop names. -- Prefer official Cloudinary docs and reference pages. -- If a question spans multiple Cloudinary products, split it into smaller doc lookups by topic. +**Note:** If a more specialized Cloudinary-specific skill covers the user's topic, defer to that skill first. Invoke this docs skill in addition, not as a substitute, and only if the full use-case also requires capabilities outside that skill's scope. + +When using this skill to answer image and video upload, management, optimization, or transformation questions or when implementing Cloudinary code: + +1. **Identify the product area**: Refer to the [Sub-file Index table](#sub-file-index-overview) above and identify the matching row. +2. **Fetch the relevant sub-file directly per the table above** (skip the main llms.txt unless the topic is cross-product or unclear) +3. **Analyze the sub-file** to identify which specific documentation URLs are most relevant +4. **Retrieve** those specific markdown documentation URLs (you can make multiple calls if needed) +5. **Use the fetched documentation** to provide a comprehensive, accurate answer or code implementation. + +## Example Workflows + +**Example 1: SDK question** +- User asks: "How do I install and use the Node.js SDK for Cloudinary?" +- Topic maps to Image & Video APIs → fetch https://cloudinary.com/documentation/llms-image-and-video-apis.txt?install_source=skillspack&referrer=docs-skill +- Identify SDK-related pages and provide installation instructions and usage examples or help implement the request in the user's code. + +**Example 2: DAM question** +- User asks: "How do I set up approval workflows for assets in the Media Library?" +- Topic maps to Cloudinary Assets (DAM) → fetch https://cloudinary.com/documentation/llms-cloudinary-assets.txt?install_source=skillspack&referrer=docs-skill +- Identify relevant pages like "dam_admin_creative_approval_flows.md" +- Fetch the specific documentation and provide setup steps + +**Example 3: MediaFlows question** +- User asks: "How do I build a PowerFlow that auto-moderates uploaded images?" +- Topic maps to MediaFlows → fetch https://cloudinary.com/documentation/llms-mediaflows.txt?install_source=skillspack&referrer=docs-skill +- Identify relevant pages like "mediaflows_build_flow.md" or "mediaflows_moderation_powerflow.md" +- Fetch the specific documentation and provide a flow-building walkthrough + +**Example 4: Integration question** +- User asks: "How do I connect Cloudinary to my WordPress site?" +- Topic maps to Integrations → fetch https://cloudinary.com/documentation/llms-integrations.txt?install_source=skillspack&referrer=docs-skill +- Identify relevant pages like "wordpress_integration.md" +- Fetch the specific documentation and provide setup instructions + +**Example 5: Ambiguous upload question** +- User asks: "How do I upload images to Cloudinary?" +- First, determine whether the user wants to upload **programmatically** (via SDK/API) or **via the Console UI** (DAM) +- If **programmatic** → fetch https://cloudinary.com/documentation/llms-image-and-video-apis.txt?install_source=skillspack&referrer=docs-skill + - Identify relevant pages like "image_upload.md" or "upload_api.md" + - Retrieve those specific pages and provide an answer with code examples +- If **via the Console UI (DAM)** → fetch https://cloudinary.com/documentation/llms-cloudinary-assets.txt?install_source=skillspack&referrer=docs-skill + - Identify relevant pages like "dam_upload_store_assets.md" or "dam_admin_upload_presets.md" + - Retrieve those specific pages and provide step-by-step instructions for uploading via the Media Library. +- If **unable to determine** → fetch https://cloudinary.com/documentation/llms.txt?install_source=skillspack&referrer=docs-skill + - Look at documentation for both Image & Video APIs and Cloudinary Assets products + - Provide an answer covering both programmatic and UI-based upload options + +**Example 6: Transformation question (fallback: use only if no specialized skill covers this topic)** +- User asks: "How do I resize and crop images?" +- Topic maps to Image & Video APIs → fetch https://cloudinary.com/documentation/llms-image-and-video-apis.txt?install_source=skillspack&referrer=docs-skill +- Identify relevant pages like "image_transformations.md" or "transformation_reference.md" +- Fetch the specific documentation and provide transformation syntax and examples or help implement the request in the user's code. \ No newline at end of file diff --git a/templates/skills/cloudinary-transformations/SKILL.md b/templates/skills/cloudinary-transformations/SKILL.md index fde9cfd..1b35ebe 100644 --- a/templates/skills/cloudinary-transformations/SKILL.md +++ b/templates/skills/cloudinary-transformations/SKILL.md @@ -1,33 +1,563 @@ --- name: cloudinary-transformations -description: turn natural-language image and video transformation requirements into valid cloudinary delivery urls and transformation strings. use when building or debugging cloudinary transformation syntax. +description: Create and debug Cloudinary transformation URLs from natural language instructions. Use when building Cloudinary delivery URLs, applying image/video transformations, optimizing media, or debugging transformation syntax errors. +license: MIT +metadata: + author: cloudinary + version: '1.0.4' --- -# Cloudinary Transformations +# Cloudinary Transformation Rules -## Purpose +## When to Use -Use this skill when you need to convert a transformation request into a valid Cloudinary URL or transformation string. +- Building Cloudinary delivery/transformation URLs +- Converting natural language requests to transformation syntax +- Debugging transformation URLs that aren't working +- Optimizing images or videos with Cloudinary +- Applying effects, overlays, resizing, or cropping -## Core workflow +## Quick Start -1. Identify the asset type and delivery goal. -2. Translate the request into transformation components in a valid order. -3. Validate crop and resize behavior, quality and format settings, effects, overlays, and video-specific parameters against official docs. -4. Check the final URL for syntax, ordering, and escaping issues. +### Default Best Practice: Always Optimize -## Rules +**Add `f_auto/q_auto` to the end of nearly every transformation URL** (as final components): +- Automatically delivers optimal format +- Optimizes quality for best balance of visual quality and file size +- Reduces bandwidth and improves performance -- Use Cloudinary transformation syntax exactly. -- Prefer documented parameters over ad hoc URL fragments. -- When a request is ambiguous, ask for the asset type, target dimensions, or intended effect behavior. -- For framework-specific wrappers, follow the wrapper docs and only fall back to raw URLs when appropriate. +**Example:** `c_fill,g_auto,w_400,h_300/f_auto/q_auto` -## Common tasks +**Exceptions - Don't add optimization when:** +- Account has "Optimize By Default" enabled (already applied automatically) +- Special quality requirements (use `q_auto:best`, `q_auto:low`, or manual `q_N` instead) +- Specific format required (replace `f_auto` with `f_png`, `f_jpg`, etc.) +- Delivering exact original with no modifications -- Resize and crop -- Format and quality optimization -- Effects and AI transformations -- Overlays and text overlays -- Video trimming and transcoding -- Debugging invalid URLs +**Examples of common transformations (with optimization):** +1. Resize: `c_scale,w_400/f_auto/q_auto` +2. Smart crop: `c_fill,g_auto,h_300,w_400/f_auto/q_auto` +3. Background removal: `e_background_removal/f_png/q_auto` +4. Text overlay: `co_yellow,l_text:Arial_40:Hello%20World/fl_layer_apply,g_south/f_auto/q_auto` +5. Image overlay: `l_logo/c_scale,w_100/fl_layer_apply,g_north_west,x_10,y_10/f_auto/q_auto` + +**Important:** All transformation strings shown throughout this skill are illustrative examples to demonstrate syntax and concepts. When generating transformations, choose specific values (dimensions, colors, positions, etc.) based on the user's actual requirements and use case, not the example values shown. + +**For debugging:** See [references/debugging.md](references/debugging.md) for detailed troubleshooting steps. + + +## Gathering Requirements + +Before generating a transformation URL, if not already specified, clarify these details based on the user's request: + +### For Resize/Crop Requests +**Required:** +- At least one dimension (width OR height) +- Crop behavior if both dimensions specified (fill, pad, scale, limit, etc.) + +**Clarify:** +- Focal point/gravity (especially for cropping): Face detection? Center? Smart auto-detection? +- Maintain aspect ratio? (if only one dimension, this is automatic) + +**Example questions:** +- "What dimensions do you need? (width and/or height)" +- "Should this fill the space (may crop) or fit within it (no cropping)?" +- "Any important focal point? (faces, center, specific area)" + +### For AI Transformation Requests +**Background removal:** +- Output format needs (PNG for transparency vs JPG with solid background) +- What to do with transparent area (keep transparent, add color, or gen_fill) + +**Generative fill:** +- Target dimensions or aspect ratio +- How much extension needed + +**Generative replace:** +- What object to replace (from) +- What to replace it with (to) +- Preserve original shape? (for clothing/objects) + +**Generative remove:** +- What object(s) to remove +- Remove all instances or just one? + +**Generative background replace:** +- Describe desired background (or use auto-generation) +- Need reproducibility? (consider seed parameter) + +### For Video Transformation Requests +**Trimming:** +- Start and end time, or duration +- Seconds or percentage of video + +**Codec/format:** +- Output format needs (MP4, WebM, etc.) +- Quality requirements (use `vc_auto` if unsure) + +**Audio:** +- Keep or remove audio track +- If for autoplay, suggest removing audio (`ac_none`) + +### Always Recommend +Unless user specifies otherwise: +- **Add `f_auto/q_auto` at the end** of transformation URLs (see Quick Start section for exceptions) +- Use `g_auto` for smart cropping when filling dimensions +- Consider cost for AI transformations (inform user of transformation credits) + +## Quick Reference + +### URL Structure + +``` +https://res.cloudinary.com//////. +``` + +**Key Rules:** +- Commas (`,`) separate parameters **within** a component +- Slashes (`/`) separate components **between** transformations +- Each component acts on the output of the previous one + +### Parameter Types + +**Action parameters**: Perform transformations (one action per component: each action transformation should be separated by a slash) +**Qualifier parameters**: Modify action behavior (in the same component as the action, using commas as separators) + +Check the [Transformation Reference](https://cloudinary.com/documentation/transformation_reference.md?install_source=skillspack&referrer=trans-skill) to determine if a parameter is an action or qualifier. + +## Core Transformations + +### Resize & Crop + +**Dimension value formats:** +- **Whole numbers** (e.g., `w_400`, `h_300`) = pixels +- **Decimal values** (e.g., `w_0.5`, `h_1.0`) = percentage of original dimensions (0.5 = 50%, 1.0 = 100%) + +**Choosing the right crop mode:** + +Use **`c_scale`** when: +- Resizing while maintaining original aspect ratio +- Specify only ONE dimension (width OR height) +- No cropping needed +- The user intentionally wants to stretch or squash an image by changing the aspect ratio + +Use **`c_fill`** when: +- Must fit exact dimensions (e.g., thumbnail grid, fixed layout) +- Okay to crop parts of image +- Combine with `g_auto` for smart cropping, or `g_face` for portraits + +Use **`c_fit`** when: +- Image must fit within dimensions without cropping +- Okay to have empty space +- Maintaining full image content is critical + +Use **`c_pad`** when: +- Must fit exact dimensions without cropping +- Need to fill empty space with background color/blur (videos only)/AI-generated pixels +- Use with `b_`, `b_auto`, `b_blurred` (blurred background - videos only), or `b_gen_fill` + +Use **`c_limit`** when: +- Set maximum dimensions but don't upscale small images +- Preserving original quality of small images matters + +Use **`c_thumb`** when: +- Creating thumbnails (typically avatars) +- Use with `g_face` for face-centered crops + +Use **`c_auto`** when: +- Cloudinary should intelligently crop to interesting content +- Combine with `g_auto` for best results +- Good for dynamic content where focal point varies + +**Examples:** +``` +c_scale,w_400 # Resize width to 400px, maintain aspect ratio +c_scale,w_0.5 # Resize to 50% of original width +c_fill,g_auto,h_300,w_400 # Fill 400x300px dimensions, smart crop +c_fit,h_300,w_400 # Fit within dimensions, no crop +c_pad,b_white,h_300,w_400 # Pad to exact size with white background +c_pad,w_1.0 # Pad to original width (100%) +c_limit,w_1000 # Limit max width, no upscale +c_thumb,g_face,h_150,w_150 # Face-centered square thumbnail +c_auto,g_auto,w_800 # Auto crop to interesting area +``` + +**Important**: Always specify a crop mode explicitly. Avoid using both dimensions with `c_scale` (will distort if aspect ratios don't match) - prefer one dimension to maintain aspect ratio. + +### Gravity (Focal Point) + +Gravity determines which part of the image to focus on when cropping: + +- **`g_auto`** - Smart detection (recommended for varied content; detects faces, objects, contrast) +- **`g_face`** - Face detection (portraits, avatars) +- **`g_center`** - Center position (centered subjects, logos) +- **`g_north`, `g_south_east`, etc.** - Compass positions (fixed locations, overlay positioning) +- **`x_N,y_N`** - Custom offsets (integers = pixels, floats = percentage: 0.8 = 80%) + +**Examples:** +``` +c_fill,g_auto,w_400,h_300 # Smart crop +c_thumb,g_face,w_200,h_200 # Face-centered +l_logo/fl_layer_apply,g_south_east,x_10,y_10 # Logo bottom-right +``` + +**Important**: +- `g_auto` only works with `c_fill`, `c_lfill`, `c_crop`, `c_thumb`, `c_auto` +- When using x, y, h, w together, use all integers OR all floats (don't mix) + +### Format & Quality + +**Recommended defaults:** +- **`f_auto/q_auto`** - Use for most production images (WebP to supported browsers, optimized file size) + +**Specific formats** (when requirements dictate): +- **`f_png`** - Transparency needed (e.g., after background removal) +- **`f_jpg`** - Force JPEG (remove transparency) +- **`q_N`** - Manual quality 1-100 (e.g., `q_60` for thumbnails, `q_90` for hero images) +- **`dpr_auto`** - Retina displays (Chromium-only, requires Client Hints - see limitations below) + +**Examples:** +``` +f_auto/q_auto # Recommended default +f_png/q_auto # PNG with transparency +q_80 # Manual 80% quality +``` + +**Best Practice**: Use `/` to separate format and quality as distinct components. + +#### Responsive Images (`dpr_auto`, `w_auto`) + +**`dpr_auto`** - Automatically adapts to device pixel ratio (Retina displays) +- **Chromium-only** (Chrome, Edge, Opera, Samsung Internet) +- Requires Client Hints configuration +- Falls back to `dpr_1.0` on other browsers +- Does NOT work inside named transformations + +**Alternative for universal support:** Use explicit `dpr_2.0` or `` with 1x/2x variants + +For Client Hints configuration, browser compatibility, responsive breakpoints, and framework integration, see [references/responsive-images.md](references/responsive-images.md) + +### Effects + +**Common effects:** +- **`e_grayscale`** - Black and white (artistic, accessibility) +- **`e_sepia`** - Vintage/nostalgic feel +- **`e_blur:N`** - Blur (privacy, placeholders; N typically 300-2000) +- **`e_sharpen`** - Enhance clarity (useful after resizing) +- **`e_cartoonify`** - Illustrated style +- **`co_rgb:RRGGBB,e_colorize:N`** - Color tint (N = intensity 0-100, for brand theming) +- **`e_background_removal`** - See AI Transformations section + +**Examples:** +``` +e_blur:800 # Blur effect +e_sharpen # Enhance clarity +co_rgb:0044ff,e_colorize:40 # Blue tint at 40% +``` + +**Note**: Color (`co_`) is a qualifier - use in same component as `e_colorize`. + +### Overlays & Underlays + +**Use for:** +- **`l_`** - Image overlays (logos, watermarks, badges) +- **`u_`** - Image underlays (custom backgrounds behind transparent subjects) +- **`l_text:font_size:text`** - Text overlays (labels, social cards, dynamic text) + +**Pattern:** +1. Declare: `l_` or `u_` or `l_text:Arial_40:Hello%20World` +2. Transform (optional): e.g. `/c_scale,w_100/` or `/o_50/` (opacity) +3. Apply: `/fl_layer_apply,g_,x_,y_` + +**Critical: Using `fl_relative` for overlay dimensions:** +- **Without `fl_relative`**: Dimensions are relative to the **overlay's original size** + - Example: `w_1.0` = 100% of the overlay image's width (not useful for small images) +- **With `fl_relative`**: Dimensions are relative to the **base image's size** + - Example: `w_1.0` = 100% of the base image's width (covers entire width) + - **Always use `fl_relative`** when sizing overlays as a percentage of the base image + +**Examples:** +``` +l_logo/c_scale,w_100/fl_layer_apply,g_north_west,x_10,y_10 # Logo at 100px +l_logo/c_scale,fl_relative,w_0.25/fl_layer_apply,g_north_west,x_10,y_10 # Logo at 25% of image width +l_docs:one_black_pixel/c_scale,fl_relative,h_1.0,w_1.0/o_50/fl_layer_apply # Full-image semi-transparent overlay +co_yellow,l_text:Arial_40:Hello%20World/fl_layer_apply,g_south # Text overlay +u_background/e_background_removal # Custom background +c_fill,h_400,w_300/l_same_image/c_fill,e_grayscale,h_400,w_300/fl_layer_apply,g_west,x_300 # Side-by-side (600×400) +``` + +**Important**: +- Color (`co_`) is a qualifier — use in the **same component** as text overlay declaration +- **Always use `fl_relative`** when you want overlay dimensions as a percentage of the base image +- **Side-by-side / canvas extension**: to place an overlay *beside* the base, offset it past the base edge — the canvas auto-expands. Use `g_west,x_` for horizontal or `g_north,y_` for vertical. + +### Borders & Rounding + +- **`r_N`** - Rounded corners (N = radius in pixels; for modern UI, cards) +- **`r_max`** - Perfect circle (use with square dimensions; avatars, icons) +- **`bo_NNpx_solid_color`** - Border (frame images, separate from background) + +**Examples:** +``` +r_20 # 20px rounded corners +r_max # Perfect circle +bo_5px_solid_black # 5px black border +r_20,bo_5px_solid_rgb:0066ff # Rounded with border (same component) +``` + +**Important**: For borders that follow rounded corners, use border as qualifier in same component. + +### Background Color + +- **`b_color,c_pad`** - Fill empty space with solid color (product images, letterboxing) +- **`b_auto,c_pad`** - Aautomatically selected background color based on one or more predominant colors in the image +- **`b_gen_fill,c_pad`** - AI-extended background (change aspect ratio without cropping; see AI Transformations for cost) + +**Examples:** +``` +b_lightblue,c_pad,w_1.0 # Light blue background +b_auto,c_pad,ar_16:9 # Automatically selected color for background, 16:9 +b_gen_fill,c_pad,ar_1:1 # AI-extended to square +b_blurred,c_pad,ar_16:9 # Blurred background (videos only), 16:9 +``` + +**Critical**: Background (`b_`) is a qualifier - use **with** pad crop in same component: `b_color,c_pad,w_X`, NOT `/b_color/`. + +### Rotation & Flips + +- **`a_90`, `a_180`, `a_270`** - Rotate in 90° increments (correct orientation) +- **`a_N`** - Rotate by degrees (e.g., `a_-2` to straighten crooked photos) +- **`a_hflip`** - Horizontal flip (mirror selfies, directional images) +- **`a_vflip`** - Vertical flip (reflections) +- **`a_auto_right`/`a_auto_left`** - Auto-rotate based on EXIF orientation + +**Examples:** +``` +a_90 # Rotate 90° clockwise +a_-2 # Straighten slight tilt +a_hflip # Mirror horizontally +a_auto_right # Auto-fix from EXIF +``` + +### Asset Type Matters (Image vs. Video) + +Many flags and parameters apply to only one asset type. Applying one to the wrong base often **fails silently** — the URL still returns a valid `200` with no `X-Cld-Error`, just the wrong output. This goes both ways: video-only syntax on an image, and image-only syntax on a video. Always verify the actual output (dimensions, duration, frame count) rather than assuming it worked. + +**Common video-only examples** (this is *not* an exhaustive list — ~35 parameters are video-only): +- **`fl_splice`** (flag) - Concatenate a clip/image onto the video timeline (no image equivalent — to place media side-by-side, offset the overlay to extend the canvas: `fl_layer_apply,g_west,x_`) +- **`du_`, `so_`, `eo_`** - Trim/seek by time (duration, start offset, end offset) +- **`fps_`** - Set frame rate +- **`vc_`, `ac_`** - Video / audio codec +- **`e_boomerang`, `e_progressbar`** - Video-only effects + +**When unsure whether a flag or parameter supports your asset type, check the [Transformation Reference](https://cloudinary.com/documentation/transformation_reference.md?install_source=skillspack&referrer=trans-skill) before applying it.** + +## Named Transformations + +Named transformations (`t_`) save transformation chains for reuse. Suggest for: +- Transformations used across multiple assets +- Complex transformation chains +- Expensive operations (to enable baseline transformations and reduce costs) + +**Baseline transformations** (`bl_`) cache expensive named transformations so they don't need to be regenerated. Use `bl_` instead of `t_` for AI transformations (background removal, generative AI) that will have variations applied. This can reduce costs from 75-230 tx per variation down to 1 tx each after the initial baseline is generated. + +**Example:** `bl_bg_removed/c_scale,w_500` - Uses cached background removal result, only pays for resize (1 tx instead of 75 tx) + +**Important:** `f_auto`, `dpr_auto`, and `w_auto` don't work inside named transformations - use them directly in URLs: `t_avatar/f_auto/q_auto` + +For complete details, limitations, and baseline transformation examples, see [references/named-transformations.md](references/named-transformations.md) + +## Generative AI Transformations + +**Proactively suggest these AI transformations when appropriate:** + +**Note:** Numbers in parentheses (e.g., 75 tx) indicate additional transformation credits consumed per use. Standard transformations = 1 tx. + +- **`e_background_removal`** (75 tx) - Remove backgrounds (e-commerce, profiles; combine with `f_png` or `b_color,c_pad`) +- **`b_gen_fill`** (50 tx) - Extend backgrounds (change aspect ratio without cropping; use with `c_pad`) +- **`e_gen_background_replace:prompt_`** (230 tx) - AI-generated backgrounds (custom environments, seasonal variations; high cost) +- **`e_gen_replace:from_;to_`** (120 tx) - Swap objects (product variations, colors; use `;preserve_geometry_true` for clothing) +- **`e_gen_remove:prompt_`** (50 tx) - Remove objects (clean up distractions) +- **`e_auto_enhance`** (100 tx) - Improve quality (fix poor lighting/exposure) +- **`e_upscale`** (10-100 tx) - Enlarge without quality loss (low-res to high-res) + +**Important:** AI transformations cost significantly more (50-230 tx vs 1 tx). Inform users of costs and consider baseline transformations (e.g., `bl_bg_removed/c_scale,w_500`) to avoid re-processing expensive operations - see [references/named-transformations.md](references/named-transformations.md#baseline-transformations) and [references/transformation-costs.md](references/transformation-costs.md) for details. + +For complete details, syntax, and powerful combinations, see [references/ai-transformations.md](references/ai-transformations.md) + +## Video-Specific Transformations + +**Critical:** Use `f_auto:video` (not just `f_auto`) to ensure video output - plain `f_auto` may return an image thumbnail. + +- **`vc_auto`** - Automatic codec (recommended; optimal for browser/device) +- **`so_N/eo_M`** - Trim (start/end in seconds; create clips, remove intro/outro) +- **`ac_none`** - Remove audio (essential for autoplay; reduces file size) +- **`fps_N`** - Set frame rate (lower = smaller file; standardize rates) +- **Video resizing** - Same crop modes as images (`c_fill`, `c_scale`, `c_pad`) + +**Common patterns:** +``` +vc_auto/ac_none/f_auto:video/q_auto # Autoplay-ready +so_0/du_10/vc_auto/f_auto:video/q_auto # First 10 seconds +c_scale,w_720/vc_auto/f_auto:video/q_auto # Resize to 720p width +c_fill,g_auto,h_720,w_1280/vc_auto/f_auto:video/q_auto # 720p HD, smart crop +``` + +For complete details including codecs, trimming strategies, and video concatenation, see [references/video-transformations.md](references/video-transformations.md) + +## Variables & Conditionals + +**Variables** reuse values and create templates: +``` +$size_300/c_fill,h_$size,w_$size # Reuse value +$iw/w_$iw_div_2 # Half original width (arithmetic) +``` + +**Conditionals** adapt transformations dynamically: +``` +if_w_gt_1000/c_scale,w_1000/if_end # Responsive sizing +if_ar_gt_1.0/c_fill,w_800,h_450/if_else/c_fill,w_450,h_800/if_end # Orientation handling +``` + +**Key rules:** +- Variable names: alphanumeric, start with letter, no underscores +- Conditionals: Must close with `if_end` +- Arithmetic: `add`, `sub`, `mul`, `div` (left-to-right evaluation) + +For complete syntax, arithmetic operations, nested conditionals, and real-world patterns, see [references/advanced-features.md](references/advanced-features.md) + +## Self-Validation Checklist + +**Before returning a transformation URL, verify:** + +1. ✅ **URL structure is complete** (cloud_name, asset_type `/image/` or `/video/` or `/raw/`, delivery_type, public_id) +2. ✅ **Each component has only one action parameter** (e.g., one crop mode per component) +3. ✅ **Crop mode is explicit** (don't rely on defaults; avoid both dimensions with `c_scale`) +4. ✅ **Overlays end with `fl_layer_apply`** in separate component +5. ✅ **Text strings are URL-encoded** (spaces = `%20`, special chars encoded) +6. ✅ **Variable names follow rules** (alphanumeric, start with letter, no underscores) +7. ✅ **`g_auto` compatibility** (only works with `c_fill`, `c_lfill`, `c_crop`, `c_thumb`, `c_auto`) +8. ✅ **Background as qualifier** (use with pad crop: `b_color,c_pad,w_X`, not `/b_color/`) +9. ✅ **Format/quality at end** (prefer `f_auto/q_auto` as final components) +10. ✅ **Flags/parameters match the base asset type** (asset-type-specific syntax — e.g. video-only `fl_splice`, `du_`, `fps_`, `vc_` — often no-ops silently on the wrong base, in either direction; verify the output and check the Asset Type Matters section above) +11. ✅ **Transformation parameters are valid** (don't make up any parameter names - check against [Transformation Reference](https://cloudinary.com/documentation/transformation_reference.md?install_source=skillspack&referrer=trans-skill)) + +**Quick syntax check:** +- Commas separate parameters within a component: `c_fill,g_auto,w_400` +- Slashes separate components: `c_fill,w_400/f_auto/q_auto` +- Actions vs qualifiers: Only one action per component, qualifiers modify that action + +See [references/debugging.md](references/debugging.md) for detailed examples of each check. + +## Debugging Checklist + +When a transformation isn't working: + +1. **Verify URL structure**: Check that all required URL parts are present: + - Cloud name: `//` + - Asset type: `/image/` or `/video/` or `/raw/` + - Delivery type: `/upload/` or `/fetch/` etc. + - Public ID at the end +2. **Check the X-Cld-Error header**: Cloudinary reports errors in the `X-Cld-Error` HTTP response header +3. **Check parameter names** against [Transformation Reference](https://cloudinary.com/documentation/transformation_reference.md?install_source=skillspack&referrer=trans-skill) +4. **Check crop mode**: Specify crop mode explicitly; avoid both dimensions with `c_scale` (causes distortion if aspect ratios don't match) +5. **Verify gravity compatibility**: `g_auto` doesn't work with `c_scale`, `c_fit`, `c_limit`, `c_pad` +6. **Check action vs qualifier**: Only one action per component, qualifiers in same component +7. **Verify overlay pattern**: Must end with `fl_layer_apply` component +8. **Check variable names**: No underscores, must start with letter +9. **Verify URL encoding**: Text overlays need URL-encoded strings (spaces = `%20`) +10. **Check auto parameters in named transformations**: `f_auto`, `dpr_auto`, and `w_auto` don't work inside named transformations - use them directly in URLs +11. **Verify Client Hints for `dpr_auto`/`w_auto`**: These only work on Chromium browsers with Client Hints enabled; fallback to `dpr_1.0` otherwise (see [references/responsive-images.md](references/responsive-images.md) for configuration) +12. **Video returns image instead of video**: Use `f_auto:video` (not just `f_auto`) for video transformations - plain `f_auto` may return an image thumbnail + +### Checking X-Cld-Error Header + +The `X-Cld-Error` header contains error details when a transformation fails. To check it: + +**Using browser DevTools:** +1. Open Developer Tools (Network tab) +2. Request the transformation URL +3. Look for `X-Cld-Error` in Response Headers + +**Using code (fetch the URL):** +```javascript +fetch('https://res.cloudinary.com/demo/image/upload/w_abc/sample.jpg') + .then(response => { + const error = response.headers.get('x-cld-error'); + if (error) { + console.log('Cloudinary Error:', error); + } + }); +``` + +**Common X-Cld-Error messages:** +- `Invalid width - abc` - Width parameter expects a number +- `Invalid transformation syntax` - Malformed transformation string +- `Resource not found` - Asset doesn't exist or public ID is incorrect +- `Transformation limit exceeded` - Account transformation quota reached + +**Online tool:** Use the [X-Cld-Error Inspector](https://cloudinary.com/documentation/advanced_url_delivery_options.md?install_source=skillspack&referrer=trans-skill#x_cld_error_inspector_tool) to check any Cloudinary URL + +For more details, see [Error Handling](https://cloudinary.com/documentation/advanced_url_delivery_options.md?install_source=skillspack&referrer=trans-skill#error_handling) + +## Transformation Costs + +**Important:** Warn users about high-cost transformations before generating URLs. AI effects cost significantly more than standard transformations (50-230 tx vs 1 tx). + +For complete cost details and cost reduction strategies, see [references/transformation-costs.md](references/transformation-costs.md) + +## Additional Resources + +### Skill References (Progressive Disclosure) +- [references/debugging.md](references/debugging.md) - Use when transformations return errors or unexpected results +- [references/ai-transformations.md](references/ai-transformations.md) - Use when you need AI transformation prompt syntax, cost details, or complex AI combinations +- [references/video-transformations.md](references/video-transformations.md) - Use when working with video codecs, trimming strategies, concatenation, or creating animated images from videos +- [references/advanced-features.md](references/advanced-features.md) - Use when building complex logic with variables, conditionals, or arithmetic +- [references/responsive-images.md](references/responsive-images.md) - Use when implementing responsive images, configuring Client Hints, or using dpr_auto/w_auto +- [references/transformation-costs.md](references/transformation-costs.md) - Use when optimizing for cost or explaining cost implications to users +- [references/named-transformations.md](references/named-transformations.md) - Use when creating reusable transformations or reducing costs for repeated operations +- [references/examples.md](references/examples.md) - Use when you need real-world examples beyond the Quick Start (social cards, e-commerce, responsive images) + +### Core Cloudinary Documentation +- [Transformation Reference](https://cloudinary.com/documentation/transformation_reference.md?install_source=skillspack&referrer=trans-skill) - All parameters + +### Image Transformations +- [Image Transformations Overview](https://cloudinary.com/documentation/image_transformations.md?install_source=skillspack&referrer=trans-skill) +- [Resizing and Cropping](https://cloudinary.com/documentation/resizing_and_cropping.md?install_source=skillspack&referrer=trans-skill) +- [Placing Layers on Images](https://cloudinary.com/documentation/layers.md?install_source=skillspack&referrer=trans-skill) +- [Effects and Enhancements](https://cloudinary.com/documentation/effects_and_artistic_enhancements.md?install_source=skillspack&referrer=trans-skill) +- [Background Removal](https://cloudinary.com/documentation/background_removal.md?install_source=skillspack&referrer=trans-skill) +- [Generative AI Transformations](https://cloudinary.com/documentation/generative_ai_transformations.md?install_source=skillspack&referrer=trans-skill) +- [Face-Detection Based Transformations](https://cloudinary.com/documentation/face_detection_based_transformations.md?install_source=skillspack&referrer=trans-skill) +- [Custom Focus Areas](https://cloudinary.com/documentation/custom_focus_areas.md?install_source=skillspack&referrer=trans-skill) +- [Transformation Refiners](https://cloudinary.com/documentation/transformation_refiners.md?install_source=skillspack&referrer=trans-skill) +- [Animated Images](https://cloudinary.com/documentation/animated_images.md?install_source=skillspack&referrer=trans-skill) +- [Transformations on 3D Models](https://cloudinary.com/documentation/transformations_on_3d_models.md?install_source=skillspack&referrer=trans-skill) +- [Conditional Transformations](https://cloudinary.com/documentation/conditional_transformations.md?install_source=skillspack&referrer=trans-skill) +- [User-Defined Variables and Arithmetic](https://cloudinary.com/documentation/user_defined_variables.md?install_source=skillspack&referrer=trans-skill) +- [Custom Functions](https://cloudinary.com/documentation/custom_functions.md?install_source=skillspack&referrer=trans-skill) + +### Video Transformations +- [Video Transformations Overview](https://cloudinary.com/documentation/video_manipulation_and_delivery.md?install_source=skillspack&referrer=trans-skill) +- [Resizing and Cropping](https://cloudinary.com/documentation/video_resizing_and_cropping.md?install_source=skillspack&referrer=trans-skill) +- [Trimming and Concatenating](https://cloudinary.com/documentation/video_trimming_and_concatenating.md?install_source=skillspack&referrer=trans-skill) +- [Placing Layers on Videos](https://cloudinary.com/documentation/video_layers.md?install_source=skillspack&referrer=trans-skill) +- [Effects and Enhancements](https://cloudinary.com/documentation/video_effects_and_enhancements.md?install_source=skillspack&referrer=trans-skill) +- [Audio Transformations](https://cloudinary.com/documentation/audio_transformations.md?install_source=skillspack&referrer=trans-skill) +- [Converting Videos to Animated Images](https://cloudinary.com/documentation/videos_to_animated_images.md?install_source=skillspack&referrer=trans-skill) +- [Conditional Transformations](https://cloudinary.com/documentation/video_conditional_expressions.md?install_source=skillspack&referrer=trans-skill) +- [User-Defined Variables and Arithmetic](https://cloudinary.com/documentation/video_user_defined_variables.md?install_source=skillspack&referrer=trans-skill) + +## Common Mistakes & Best Practices + +**Avoid:** +- ❌ `w_400,h_300` → ✅ `c_scale,w_400` (both dimensions with c_scale distorts image; prefer one dimension) +- ❌ `c_scale,g_auto,w_400` → ✅ `c_fill,g_auto,w_400` (g_auto doesn't work with c_scale) +- ❌ `l_logo/fl_layer_apply,g_north_west` → ✅ `l_logo/c_scale,w_100/fl_layer_apply,g_north_west` +- ❌ `b_lightblue/e_trim` → ✅ `b_lightblue,c_pad,w_1.0/e_trim` (background as qualifier) + +**Always:** +- Prefer `f_auto/q_auto` in separate components over `f_auto,q_auto` +- Use `g_auto` for smart cropping unless specific focal point needed +- Specify crop mode with width/height; prefer one dimension with `c_scale` +- Never guess parameter names - verify against documentation diff --git a/templates/skills/cloudinary-transformations/references/advanced-features.md b/templates/skills/cloudinary-transformations/references/advanced-features.md new file mode 100644 index 0000000..e3d6d0a --- /dev/null +++ b/templates/skills/cloudinary-transformations/references/advanced-features.md @@ -0,0 +1,727 @@ +# Advanced Features: Variables, Conditionals & Arithmetic + +This reference covers advanced Cloudinary transformation capabilities for building dynamic, template-based, and conditional transformations. + +## Variables + +Variables allow you to reuse values across a transformation chain and create template transformations that adapt to asset properties. + +### Basic Variable Syntax + +**Declaration and usage:** +``` +$varName_value/...use_$varName... +``` + +**Rules:** +- Variable names: alphanumeric only, must start with letter +- **NO underscores in variable names** (❌ `$my_width` ✅ `$mywidth`) +- Values can be numeric or string (strings use `!` delimiters) +- Declare before use (left to right in URL) + +### Numeric Variables + +**Simple value reuse:** +``` +$size_300/c_fill,h_$size,w_$size +``` +Creates a 300x300 square. Change `$size_300` once to update both dimensions. + +**Multiple variables:** +``` +$width_800,$height_600/c_fill,h_$height,w_$width/f_auto/q_auto +``` +Template for any dimensions. + +**Padding/offset consistency:** +``` +$pad_50/l_logo/c_scale,w_100/fl_layer_apply,g_north_west,x_$pad,y_$pad/f_auto/q_auto +``` +Logo positioned with consistent 50px padding from edges. + +### String Variables + +**Syntax:** Use `!` delimiters for string values +``` +$color_!blue!/b_$color,c_pad,w_1.0/f_auto/q_auto +$text_!Hello World!/l_text:Arial_40:$text/fl_layer_apply/f_auto/q_auto +``` + +**Important:** Spaces in string variables are preserved, no URL encoding needed in declaration. + +**Text interpolation:** Use `$(varName)` syntax in text overlays +``` +$date_25/co_white,l_text:Arial_60:Day%20$(date)/fl_layer_apply,g_center/f_auto/q_auto +``` + +### Asset Property Variables + +Access original asset properties using predefined variables: + +**Dimension variables:** +- `$iw` - Initial width (original width in pixels) +- `$ih` - Initial height (original height in pixels) +- `$ar` - Aspect ratio (width/height, e.g., 1.5 for 3:2 ratio) +- `$cp` - Current page/layer number (for PDFs, multi-page TIFFs) +- `$tags` - Asset tags (use in conditionals) + +**Examples:** +``` +$iw/w_$iw_div_2/f_auto/q_auto # Half original width +$iw,$ih/c_scale,w_$iw,h_$ih_div_2/f_auto/q_auto # Half original height +$ar/c_fill,ar_$ar,w_800/f_auto/q_auto # Maintain original aspect ratio +``` + +**Use cases:** +- Relative sizing: resize based on original dimensions +- Maintain proportions: preserve original aspect ratio while resizing +- Responsive templates: one URL adapts to any asset size + +### Metadata and Context Variables + +**Structured metadata:** +``` +$title_!md:title!/co_white,l_text:Arial_50:$(title)/fl_layer_apply,g_north/f_auto/q_auto +``` +Overlays text from asset's metadata field `title`. + +**Context variables:** +``` +$category_!ctx:category!/if_ctx:!category!_eq_!featured!/e_saturation:50/if_end/f_auto/q_auto +``` +Conditional transformation based on context variable. + +**Common metadata fields:** +- `md:title`, `md:description`, `md:price`, `md:stock`, `md:date` +- Must be set on asset via [structured metadata](https://cloudinary.com/documentation/structured_metadata.md?install_source=skillspack&referrer=trans-skill) + +### Variable Scope and Order + +**Variables are scoped left-to-right:** +``` +✅ $size_300/c_fill,h_$size,w_$size # Declared before use +❌ c_fill,h_$size,w_$size/$size_300 # Used before declaration +``` + +**Variables persist across components:** +``` +$brand_!0066ff!/bo_3px_solid_rgb:$brand,c_fill,h_400,w_600/co_rgb:$brand,l_text:Arial_40:Brand/fl_layer_apply/f_auto/q_auto +``` +Brand color used in multiple components. + +## Arithmetic Operations + +Perform calculations on dimensions using asset properties or variables. + +### Basic Operators + +- `add` - Addition: `w_add_100` (width + 100px) +- `sub` - Subtraction: `h_sub_50` (height - 50px) +- `mul` - Multiplication: `w_mul_2` (width × 2) +- `div` - Division: `w_div_2` (width ÷ 2) + +**Examples:** +``` +c_scale,w_iw_div_2/f_auto/q_auto # Half original width +c_crop,h_ih_sub_100,w_iw/f_auto/q_auto # Crop 100px from height +c_scale,w_mul_1.5/f_auto/q_auto # 150% of original width +``` + +### Chaining Operations + +**Multiple operations in sequence:** +``` +c_scale,w_iw_div_2_mul_3/f_auto/q_auto # (width ÷ 2) × 3 +c_scale,w_iw_sub_100_div_2/f_auto/q_auto # (width - 100) ÷ 2 +``` + +**Order of operations:** Left to right, no precedence + +### Practical Arithmetic Examples + +**Create responsive padding:** +``` +$pad_iw_mul_0.05/l_logo/fl_layer_apply,g_north_west,x_$pad,y_$pad/f_auto/q_auto +``` +Logo padding is 5% of original width. + +**Maintain aspect ratio with constraints:** +``` +c_scale,w_800,h_800_div_ar/f_auto/q_auto +``` +Width fixed at 800px, height calculated from aspect ratio. + +**Add borders relative to size:** +``` +$border_iw_div_100/bo_$(border)px_solid_black/f_auto/q_auto +``` +Border thickness is 1% of image width. + +### Using Arithmetic with Variables + +``` +$base_200/c_fill,h_$base,w_$base_mul_2/f_auto/q_auto +``` +Creates 200×400 rectangle (height = $base, width = $base × 2). + +``` +$margin_iw_mul_0.1/l_badge/fl_layer_apply,g_north_east,x_$margin,y_$margin/f_auto/q_auto +``` +Badge positioned with 10% margin relative to image width. + +## Conditionals + +Build responsive, adaptive transformations that change based on asset properties, tags, metadata, or context. + +### Basic Conditional Syntax + +``` +if_/...transformations.../if_end +if_/...true_branch.../if_else/...false_branch.../if_end +``` + +**Critical:** Every `if_` must close with `if_end` + +### Comparison Operators + +- `eq` - Equal to +- `ne` - Not equal to +- `lt` - Less than +- `lte` - Less than or equal +- `gt` - Greater than +- `gte` - Greater than or equal + +**Examples:** +``` +if_w_gt_1000/c_scale,w_1000/if_end # Downsize large images +if_ar_eq_1.0/r_max/if_end # Circle if square +if_fc_gte_1/c_thumb,g_face,w_200/if_end # Face-centered if face detected +``` + +### Logical Operators + +**AND** - Both conditions must be true: +``` +if_w_gt_800_and_h_gt_600/c_fill,h_600,w_800/if_end +``` + +**OR** - Either condition must be true: +``` +if_w_gt_2000_or_h_gt_2000/c_limit,w_2000/if_end +``` + +**Precedence:** AND has higher precedence than OR +``` +if_A_and_B_or_C # Evaluates as: (A AND B) OR C +``` + +### Dimension-Based Conditionals + +**Width and height:** +``` +if_w_gt_1000/c_scale,w_1000/if_end # Limit max width +if_h_lt_500/c_fit,h_500,w_800/if_end # Ensure min height +if_w_gte_1920_and_h_gte_1080/q_90/if_else/q_auto/if_end # Higher quality for large images +``` + +**Aspect ratio:** +``` +if_ar_gt_1.0/c_fill,h_400,w_800/if_else/c_fill,h_800,w_400/if_end +``` +Different crops for landscape (ar > 1.0) vs portrait (ar ≤ 1.0). + +``` +if_ar_gt_1.5/c_crop,ar_16:9/if_else/c_pad,ar_16:9,b_auto/if_end +``` +Crop wide images to 16:9, pad narrower images. + +### Tag-Based Conditionals + +**Check for tag presence:** +``` +if_!sale!_in_tags/l_sale_badge/fl_layer_apply,g_north_east/if_end/f_auto/q_auto +``` + +**Check for tag absence:** +``` +if_!premium!_nin_tags/l_watermark/fl_layer_apply,g_center/if_end/f_auto/q_auto +``` + +**Multiple tags (AND logic):** +``` +if_!sale:featured!_in_tags/e_saturation:50/if_end/f_auto/q_auto +``` +Both "sale" AND "featured" tags must be present (colon = AND). + +**Important:** Tag values must be wrapped in `!` delimiters. + +### Face Count Conditionals + +**Face detection:** +``` +if_fc_gt_0/c_thumb,g_face,h_200,w_200/if_else/c_fill,g_auto,h_200,w_200/if_end/f_auto/q_auto +``` +Uses face detection if faces found, otherwise smart crop. + +``` +if_fc_eq_1/c_thumb,g_face,h_300,w_300/if_else/c_fill,g_faces,h_300,w_400/if_end/f_auto/q_auto +``` +Single face: square crop. Multiple faces: wider crop to include all. + +### Metadata-Based Conditionals + +**Numeric metadata:** +``` +if_md:!price!_gt_100/l_premium_badge/fl_layer_apply,g_north_west/if_end/f_auto/q_auto +``` + +**String metadata:** +``` +if_md:!category!_eq_!electronics!/e_sharpen:100/if_end/f_auto/q_auto +``` + +**Combined conditions:** +``` +if_md:!stock!_gt_0_and_md:!featured!_eq_!true!/l_featured_badge/fl_layer_apply/if_end/f_auto/q_auto +``` +Badge only if in stock AND featured. + +### Context-Based Conditionals + +**Context variables** (set at request time): +``` +if_ctx:!theme!_eq_!dark!/e_brightness:20/if_end/f_auto/q_auto +``` + +**Use cases:** +- A/B testing: different transformations per variant +- Personalization: adapt to user preferences +- Multi-tenant: brand-specific overlays + +### Nested Conditionals + +**Pattern:** Conditionals can be nested for complex logic +``` +if_w_gt_1000/if_ar_gt_1.5/c_crop,ar_16:9/if_else/c_scale,w_1000/if_end/if_end/f_auto/q_auto +``` +If wide (>1000px), check aspect ratio and handle accordingly. + +**Best practice:** Keep nesting shallow (2-3 levels max) for maintainability. + +### Complex Conditional Examples + +**Art direction with fallback:** +``` +if_ar_gt_2.0/c_crop,ar_16:9/if_else/if_ar_lt_0.5/c_pad,ar_9:16,b_auto/if_else/c_scale,w_800/if_end/if_end/f_auto/q_auto +``` +- Very wide (ar > 2.0): Crop to 16:9 +- Very tall (ar < 0.5): Pad to 9:16 with blur +- Normal: Scale to 800px width + +**Quality optimization by size:** +``` +if_w_gt_2000_or_h_gt_2000/q_90/if_else/if_w_lt_500/q_70/if_else/q_auto/if_end/if_end/f_auto +``` +- Large (>2000px): q_90 +- Small (<500px): q_70 +- Normal: q_auto + +**Face-aware with density check:** +``` +if_fc_eq_0/c_fill,g_auto,h_400,w_600/if_else/if_fc_lt_3/c_thumb,g_face,h_400,w_600/if_else/c_fill,g_faces,h_400,w_800/if_end/if_end/f_auto/q_auto +``` +- No faces: Smart crop +- 1-2 faces: Face-centered crop +- 3+ faces: Wider crop to include all faces + +## Arithmetic Expressions + +Perform calculations on dimensions, positions, and other numeric parameters. + +### Available Operators + +- `add` - Addition +- `sub` - Subtraction +- `mul` - Multiplication +- `div` - Division +- `pow` - Power/exponent + +### Basic Arithmetic + +**Division:** +``` +c_scale,w_div_2/f_auto/q_auto # Half width +w_iw_div_2 # Half of initial width +``` + +**Multiplication:** +``` +c_scale,w_mul_1.5/f_auto/q_auto # 150% width +w_iw_mul_2 # Double initial width +``` + +**Addition:** +``` +c_crop,h_add_100,w_800/f_auto/q_auto # Add 100px to height +w_iw_add_200 # Initial width + 200px +``` + +**Subtraction:** +``` +c_crop,h_sub_50,w_800/f_auto/q_auto # Subtract 50px from height +h_ih_sub_100 # Initial height - 100px +``` + +### Chained Arithmetic + +**Multiple operations (left-to-right evaluation):** +``` +w_iw_div_2_mul_3 # (initial_width ÷ 2) × 3 +h_ih_sub_100_div_2 # (initial_height - 100) ÷ 2 +w_iw_mul_0.8_add_50 # (initial_width × 0.8) + 50 +``` + +**Order matters:** +``` +w_100_add_50_mul_2 # (100 + 50) × 2 = 300 +w_100_mul_2_add_50 # (100 × 2) + 50 = 250 +``` + +### Aspect Ratio Calculations + +**Calculate height from width:** +``` +c_scale,w_800,h_800_div_ar/f_auto/q_auto +``` +Height = 800 ÷ aspect_ratio (maintains proportions). + +**Calculate width from height:** +``` +c_scale,h_600,w_600_mul_ar/f_auto/q_auto +``` +Width = 600 × aspect_ratio (maintains proportions). + +**Adjust aspect ratio:** +``` +c_crop,ar_ar_mul_1.5/f_auto/q_auto +``` +Makes image 50% wider while maintaining height. + +### Using Arithmetic with Variables + +**Combine variables and arithmetic:** +``` +$base_200/c_fill,h_$base,w_$base_mul_2/f_auto/q_auto +``` +Creates 200×400 rectangle (width = base × 2). + +**Complex calculations:** +``` +$margin_iw_mul_0.05,$size_iw_mul_0.25/l_logo/c_scale,w_$size/fl_layer_apply,g_north_east,x_$margin,y_$margin/f_auto/q_auto +``` +Logo size is 25% of image width, margin is 5% of image width. + +**Responsive overlay positioning:** +``` +$offset_iw_sub_200_div_2/l_badge/fl_layer_apply,g_north,x_$offset/f_auto/q_auto +``` +Centers 200px badge horizontally: offset = (width - 200) ÷ 2. + +## Real-World Advanced Patterns + +### Template Transformation with Multiple Variables + +``` +$w_800,$h_600,$brand_!0066ff!,$opacity_70/c_fill,h_$h,w_$w/bo_5px_solid_rgb:$brand,co_rgb:$brand,l_text:Arial_50_bold:$(brand)/fl_layer_apply,g_south,o_$opacity,y_30/f_auto/q_auto +``` +Complete template: dimensions, brand color for border and text, custom opacity. + +### Responsive Watermark Sizing + +``` +$wmsize_iw_mul_0.15/l_watermark/c_scale,fl_relative,w_$wmsize/fl_layer_apply,g_south_east,x_20,y_20/f_auto/q_auto +``` +Watermark scales to 15% of image width (responsive to any size). + +### Conditional Quality Based on Size + +``` +if_w_gt_2000_or_h_gt_2000/q_90/if_else/if_w_lt_400_or_h_lt_400/q_70/if_else/q_auto/if_end/if_end/f_auto +``` +- Very large images: High quality (90) +- Very small images: Lower quality (70) +- Normal images: Automatic + +### Dynamic Cropping Based on Orientation + +``` +$targetw_800,$targeth_600/if_ar_gt_ar_calc_$targetw_div_$targeth/c_fill,h_$targeth,w_$targetw/if_else/c_fit,h_$targeth,w_$targetw/if_end/f_auto/q_auto +``` +Fill if aspect ratio matches target, otherwise fit. + +### Smart Thumbnail Generation + +``` +$size_300/if_fc_gt_0/c_thumb,g_face,h_$size,w_$size/r_max/if_else/c_fill,g_auto,h_$size,w_$size/r_20/if_end/f_auto/q_auto +``` +- Face detected: Circular face thumbnail +- No face: Rounded square with smart crop + +### Responsive Text Overlay + +``` +$fontsize_iw_div_10/co_white,l_text:Arial_$(fontsize)_bold:SALE/b_red,fl_layer_apply,g_north/f_auto/q_auto +``` +Font size scales to 10% of image width. + +**Note:** Font size must be an integer. Use variables carefully with arithmetic to ensure valid values. + +### Conditional Overlay Based on Tags + +``` +if_!watermark!_nin_tags/if_!premium!_in_tags/l_premium_badge/fl_layer_apply,g_north_east/if_end/if_end/f_auto/q_auto +``` +- Skip everything if "watermark" tag present +- Add premium badge if "premium" tag present + +### Aspect Ratio Preservation with Max Size + +``` +$maxdim_1200/if_w_gt_h/c_scale,w_$maxdim/if_else/c_scale,h_$maxdim/if_end/f_auto/q_auto +``` +Scales longest dimension to 1200px while preserving aspect ratio. + +### E-commerce Product Variations + +``` +$size_800/if_md:!category!_eq_!apparel!/c_pad,ar_3:4,b_white,h_$size,w_$size_mul_0.75/if_else/c_pad,ar_1:1,b_white,h_$size,w_$size/if_end/f_auto/q_auto +``` +- Apparel products: 3:4 ratio (portrait) +- Other products: 1:1 ratio (square) + +### Seasonal Overlay Based on Context + +``` +$season_!ctx:season!/if_ctx:!season!_eq_!winter!/l_snowflake/fl_layer_apply,g_north_west/if_else/if_ctx:!season!_eq_!summer!/l_sun/fl_layer_apply,g_north_west/if_end/if_end/f_auto/q_auto +``` +Different seasonal icons based on context. + +## Best Practices + +### Variable Naming + +**Good names:** +- ✅ `$width`, `$size`, `$margin`, `$brand`, `$opacity` +- ✅ Start with letter, descriptive, lowercase + +**Bad names:** +- ❌ `$my_width` (underscores not allowed) +- ❌ `$1size` (must start with letter) +- ❌ `$w` (too cryptic, prefer `$width`) + +### When to Use Variables + +**Use variables when:** +- Same value used multiple times (DRY principle) +- Building reusable templates +- Calculating relative values (percentages, ratios) +- Simplifying complex transformation chains + +**Don't use variables when:** +- Value only used once (unnecessary complexity) +- Simple static transformations + +### When to Use Conditionals + +**Use conditionals when:** +- Different transformations needed for different asset types +- Responsive behavior based on dimensions +- Tag-based variations (sale items, featured content) +- Metadata-driven transformations (pricing tiers, categories) +- Protecting against edge cases (very small/large images) + +**Don't use conditionals when:** +- Simple static transformation works for all cases +- Can handle variation with single flexible transformation (e.g., `c_fit` vs complex conditional) + +### Performance Considerations + +**Conditionals are evaluated at delivery time:** +- No extra cost for conditional logic itself +- Only the executed branch counts toward transformation credits +- Good for reducing unnecessary transformations + +**Variables add minimal overhead:** +- Negligible performance impact +- Improve maintainability of complex URLs +- Consider named transformations for frequently used variable combinations + +## Debugging Advanced Features + +### Variable Issues + +**Variable not working:** +1. Check variable name has no underscores +2. Verify variable declared before use +3. Check syntax: `$name_value` for declaration, `$name` for reference +4. For strings: Ensure `!` delimiters used + +**Text interpolation not working:** +1. Use `$(varName)` syntax in text overlays, not just `$varName` +2. Ensure URL encoding for rest of text: `Day%20$(date)` + +### Conditional Issues + +**Conditional not applying:** +1. Verify condition syntax matches operators exactly +2. Check for missing `if_end` +3. Verify tag/metadata delimiters (`!` for strings) +4. Test condition values (are they actually true?) + +**Nested conditionals not working:** +1. Count `if_` and `if_end` pairs (must match) +2. Check `if_else` placement (between branches, not after `if_end`) +3. Simplify: Test each condition separately first + +### Arithmetic Issues + +**Calculation not working:** +1. Check operator spelling: `div` not `divide` +2. Verify asset property names: `iw`, `ih`, `ar` (not `width`, `height`) +3. Check order of operations (left-to-right) +4. Ensure result is valid for parameter (e.g., dimensions must be positive integers) + +**Division by zero:** +``` +❌ w_10_div_0 # Invalid +✅ w_iw_div_2 # Safe (iw is always > 0) +``` + +## Advanced Examples Library + +### Responsive Image Grid + +``` +$cols_3,$gutter_20,$container_1200,$slots_$cols_add_1,$totalgutter_$slots_mul_$gutter,$avail_$container_sub_$totalgutter/c_fill,g_auto,w_$avail_div_$cols/if_ar_gt_1.0/c_fill,ar_16:9,w_$avail_div_$cols/if_else/c_fill,ar_1:1,w_$avail_div_$cols/if_end/f_auto/q_auto +``` +Calculates grid item width: (container - (gutter × (cols + 1))) ÷ cols + +### Progressive Enhancement + +``` +if_w_gt_1920/c_scale,w_1920/q_90/if_else/if_w_gt_1200/c_scale,w_1200/q_85/if_else/c_scale,w_800/q_auto/if_end/if_end/f_auto +``` +Tiered quality based on size. + +### Smart Product Thumbnails + +``` +$size_400/if_fc_gt_0/c_crop,g_face,h_$size,w_$size/if_else/if_ar_gt_1.2/c_fill,g_auto,h_$size,w_$size_mul_1.3/if_else/if_ar_lt_0.8/c_fill,g_auto,h_$size_mul_1.3,w_$size/if_else/c_fill,g_auto,h_$size,w_$size/if_end/if_end/if_end/f_auto/q_auto +``` +- Face: Face-centered square +- Landscape: Slightly wider +- Portrait: Slightly taller +- Square: Standard square + +### Dynamic Watermark Placement + +``` +$wmw_iw_mul_0.3,$wmh_ih_mul_0.1,$xpos_iw_sub_$wmw_sub_30,$ypos_ih_sub_$wmh_sub_30/l_watermark/c_scale,h_$wmh,w_$wmw/fl_layer_apply,x_$xpos,y_$ypos/f_auto/q_auto +``` +Watermark sized to 30% width × 10% height, positioned 30px from bottom-right. + +### Conditional Padding Strategy + +``` +if_ar_gt_1.5/c_pad,ar_16:9,b_auto/if_else/if_ar_lt_0.67/c_pad,ar_9:16,b_auto/if_else/c_fit,w_800/if_end/if_end/f_auto/q_auto +``` +- Wide images: Pad to 16:9 with automatically selected color +- Tall images: Pad to 9:16 with automatically selected color +- Normal: Fit to 800px + +## Limitations and Gotchas + +### Variable Limitations + +1. **No recursive references**: Can't use a variable in its own definition + ``` + ❌ $size_$size_mul_2 # Invalid + ``` + +2. **No string arithmetic**: Can't perform math on string variables + ``` + ❌ $text_!Hello!/$newtext_$text_add_!World! # Invalid + ``` + +3. **Integer results**: Some parameters require integers (font size, dimensions) + ``` + ⚠️ $fontsize_iw_div_7.5 # May produce decimals, font size needs integer + ``` + +### Conditional Limitations + +1. **No else-if**: Use nested conditionals instead + ``` + ❌ if_A/X/else_if_B/Y/else/Z/if_end # Not supported + ✅ if_A/X/if_else/if_B/Y/if_else/Z/if_end/if_end # Use nested + ``` + +2. **Evaluation order**: AND has higher precedence than OR + ``` + if_A_or_B_and_C # Evaluates as: A OR (B AND C) + ``` + +3. **Max nesting depth**: Keep practical (2-3 levels for readability) + +### Arithmetic Limitations + +1. **Left-to-right only**: No operator precedence + ``` + w_100_add_50_mul_2 # (100 + 50) × 2, not 100 + (50 × 2) + ``` + +2. **Division truncates**: Results are integers + ``` + w_100_div_3 # Result: 33 (not 33.333...) + ``` + +3. **No parentheses**: Can't group operations + ``` + ❌ w_(100_add_50)_mul_2 # Not supported + ✅ w_100_add_50_mul_2 # Left-to-right: (100 + 50) × 2 + ``` + +## When to Use Advanced Features + +### Use Variables When: +- Building transformation templates for consistency +- Same value appears multiple times +- Calculating relative dimensions (responsive sizing) +- Simplifying complex overlay positioning + +### Use Conditionals When: +- Asset properties vary widely (dimensions, aspect ratios) +- Tag-based variations needed (sales, featured items) +- Metadata-driven transformations (categories, pricing) +- Responsive transformations for different screen sizes +- Protecting against edge cases + +### Use Arithmetic When: +- Resizing relative to original dimensions +- Calculating proportional overlays/padding +- Maintaining aspect ratios with constraints +- Creating responsive designs + +### Consider Named Transformations Instead When: +- Transformation is static and reused frequently +- No dynamic values needed +- Simpler maintenance than complex variable/conditional chains + +For named transformation details, see [named-transformations.md](named-transformations.md) + +## Additional Resources + +- [Conditional Transformations](https://cloudinary.com/documentation/conditional_transformations.md?install_source=skillspack&referrer=trans-skill) - Complete conditional syntax +- [User-Defined Variables and Arithmetic](https://cloudinary.com/documentation/user_defined_variables.md?install_source=skillspack&referrer=trans-skill) - Full variable reference +- [Structured Metadata](https://cloudinary.com/documentation/structured_metadata.md?install_source=skillspack&referrer=trans-skill) - Using metadata in conditionals +- [Context Variables](https://cloudinary.com/documentation/user_defined_variables.md?install_source=skillspack&referrer=trans-skill#context_variables) - Request-time variables diff --git a/templates/skills/cloudinary-transformations/references/ai-transformations.md b/templates/skills/cloudinary-transformations/references/ai-transformations.md new file mode 100644 index 0000000..07f6f8d --- /dev/null +++ b/templates/skills/cloudinary-transformations/references/ai-transformations.md @@ -0,0 +1,133 @@ +# Generative AI Transformations + +Cloudinary's AI transformations solve common business challenges. **Proactively suggest these when appropriate:** + +## Background Removal (`e_background_removal`) +**Cost:** 75 tx | **Use when:** Product images, portraits, preparing for overlays +**Value:** Professional product photos without manual editing + +``` +e_background_removal/f_png +``` + +## Generative Fill (`b_gen_fill`) +**Cost:** 50 tx | **Use when:** Changing aspect ratios without cropping, extending images +**Value:** Adapt one image to multiple formats without reshooting + +``` +c_pad,ar_16:9,b_gen_fill,w_1200/f_auto/q_auto +``` + +## Auto Enhance (`e_auto_enhance`) +**Cost:** 100 tx | **Use when:** Improving UGC quality, correcting lighting/exposure +**Value:** Professional-looking images without manual photo editing + +``` +e_auto_enhance/f_auto/q_auto +``` + +## Upscale (`e_upscale`) +**Cost:** 10-100 tx | **Use when:** Enlarging images without quality loss +**Value:** Use existing images at larger sizes for print or displays + +``` +e_upscale/c_scale,w_2000/f_auto/q_auto +``` + +## Generative Background Replace (`e_gen_background_replace`) +**Cost:** 230 tx | **Use when:** Replacing backgrounds with AI-generated environments +**Value:** Create contextual product imagery without photoshoots + +``` +e_gen_background_replace:prompt_modern office space/f_auto/q_auto +e_gen_background_replace:prompt_;seed_ # Use seed for reproducibility +``` + +**Key notes:** +- Auto-detects/preserves foreground on non-transparent images +- For transparent images, fills transparent area +- Not supported for animated/fetched images + +## Generative Replace (`e_gen_replace`) +**Cost:** 120 tx | **Use when:** Swapping objects, A/B testing product variations +**Value:** Create product variations instantly without reshoots + +``` +e_gen_replace:from_shirt;to_cable knit sweater;preserve-geometry_true +e_gen_replace:from_;to_;multiple_true # Replace all instances +``` + +**Key notes:** +- Use `preserve-geometry_true` to maintain shape (ideal for clothing) +- Don't use for faces, hands, or text +- Only works on non-transparent images + +## Generative Restore (`e_gen_restore`) +**Cost:** 100 tx | **Use when:** Restoring old photos, fixing compression artifacts +**Value:** Revitalize low-quality or historical content at scale + +``` +e_gen_restore/f_auto/q_auto +``` + +**Key notes:** Removes artifacts, reduces noise, sharpens, recovers detail + +## Generative Remove (`e_gen_remove`) +**Cost:** 50 tx | **Use when:** Removing unwanted objects, cleaning product photos +**Value:** Clean up images at scale without manual editing + +``` +e_gen_remove:prompt_the stick/f_auto/q_auto +e_gen_remove:prompt_goose;multiple_true # Remove all instances +e_gen_remove:prompt_(text;person) # Remove multiple types +``` + +**Key notes:** Parentheses syntax removes multiple different objects simultaneously + +## When to Suggest AI Transformations + +**Proactively recommend:** +- "Remove background" → `e_background_removal` +- "Replace background" → `e_gen_background_replace:prompt_` +- "Change aspect ratio without cropping" → `b_gen_fill` with `c_pad` +- "Swap object/change color" → `e_gen_replace:from_;to_` +- "Fix old photo/restore" → `e_gen_restore` +- "Remove object" → `e_gen_remove:prompt_` +- "Improve quality" → `e_auto_enhance` +- "Make bigger" → `e_upscale` + +## Powerful AI Combinations + +``` +e_background_removal/e_gen_background_replace:prompt_modern office/f_auto/q_auto +e_gen_remove:prompt_price tag/e_background_removal/b_white,c_pad,w_1.0/e_auto_enhance/f_auto/q_auto +e_gen_restore/e_upscale/c_scale,w_2000/f_auto/q_auto +e_background_removal/b_gen_fill,c_pad,ar_16:9,w_1200/e_auto_enhance/f_auto/q_auto +``` + +## Cost Optimization with Baseline Transformations + +Since AI transformations are expensive (50-230 tx), use **baseline transformations** to cache results and avoid re-processing: + +**Example: Background removal with multiple variations** +``` +# Without baseline - regenerates background removal each time (75 tx each) +e_background_removal/c_scale,w_500/f_auto/q_auto # 75 tx +e_background_removal/c_fill,h_300,w_400/f_auto/q_auto # 75 tx +e_background_removal/e_grayscale/f_auto/q_auto # 75 tx +# Total: 225 tx + +# With baseline - processes background removal once (75 tx + 1 tx per variation) +# Named transformation "bg_removed" contains: e_background_removal/f_jxl/q_100 +bl_bg_removed/c_scale,w_500/f_auto/q_auto # 1 tx +bl_bg_removed/c_fill,h_300,w_400/f_auto/q_auto # 1 tx +bl_bg_removed/e_grayscale/f_auto/q_auto # 1 tx +# Total: 78 tx (75 tx for baseline + 3 tx for variations) +``` + +**When to suggest baseline transformations:** +- User needs multiple variations of an AI-transformed image +- Expensive AI operations will be reused (background removal, generative AI, upscale) +- Building a product catalog with consistent AI processing + +For complete syntax, rules, and implementation details, see [named-transformations.md](named-transformations.md#baseline-transformations) diff --git a/templates/skills/cloudinary-transformations/references/debugging.md b/templates/skills/cloudinary-transformations/references/debugging.md new file mode 100644 index 0000000..d593a44 --- /dev/null +++ b/templates/skills/cloudinary-transformations/references/debugging.md @@ -0,0 +1,528 @@ +# Debugging Cloudinary Transformations + +Common issues and their solutions when transformations don't work as expected. + +## Syntax Errors + +### Issue: Both Dimensions Without Explicit Crop Mode +⚠️ **Works but risky:** +``` +w_400,h_300 +``` + +✅ **Better:** +``` +c_scale,w_400 # Specify one dimension, maintain aspect ratio +``` +or +``` +c_fill,h_300,w_400 # Both dimensions needed, smart crop +``` + +**Why:** While `c_scale` is the default crop mode, specifying both dimensions with `c_scale` (explicit or default) will distort the image if the aspect ratio doesn't match the original. Best practice: specify the crop mode explicitly and prefer one dimension with `c_scale` to maintain aspect ratio. + +### Issue: Invalid Parameter Names +❌ **Wrong:** +``` +crop_scale,width_400 +``` + +✅ **Correct:** +``` +c_scale,w_400 +``` + +**Why:** Cloudinary uses abbreviated parameter names. Always check the [Transformation Reference](https://cloudinary.com/documentation/transformation_reference.md?install_source=skillspack&referrer=trans-skill). + +## Gravity Issues + +### Issue: g_auto Not Working +❌ **Wrong:** +``` +c_scale,g_auto,w_400 +``` + +✅ **Correct:** +``` +c_fill,g_auto,w_400 +``` + +**Why:** `g_auto` only works with: `c_fill`, `c_lfill`, `c_fill_pad`, `c_crop`, `c_thumb`, `c_auto`, `c_auto_pad` + +**Does NOT work with:** `c_scale`, `c_fit`, `c_limit`, `c_mfit`, `c_pad`, `c_lpad`, `c_mpad` + +### Issue: g_auto on Overlays +❌ **Wrong:** +``` +l_logo/c_scale,w_100/fl_layer_apply,g_auto +``` + +✅ **Correct:** +``` +l_logo/c_scale,w_100/fl_layer_apply,g_north_west,x_10,y_10 +``` + +**Why:** `g_auto` doesn't work for positioning overlays. Use compass directions or `g_center`. + +## Overlay Issues + +### Issue: Overlay Not Appearing +❌ **Wrong:** +``` +l_logo/c_scale,w_100 +``` + +✅ **Correct:** +``` +l_logo/c_scale,w_100/fl_layer_apply,g_north_west +``` + +**Why:** Every overlay must end with a `fl_layer_apply` component. + +### Issue: Overlay Positioning in Wrong Component +❌ **Wrong:** +``` +l_logo,g_north_west/c_scale,w_100/fl_layer_apply +``` + +✅ **Correct:** +``` +l_logo/c_scale,w_100/fl_layer_apply,g_north_west +``` + +**Why:** Positioning parameters (`g_`, `x_`, `y_`) go in the `fl_layer_apply` component, not the layer declaration. + +### Issue: Multiple Overlays Missing fl_layer_apply +❌ **Wrong:** +``` +l_logo/c_scale,w_100/l_badge/c_scale,w_60/fl_layer_apply,g_north_west +``` + +✅ **Correct:** +``` +l_logo/c_scale,w_100/fl_layer_apply,g_north_west,x_10,y_10/l_badge/c_scale,w_60/fl_layer_apply,g_north_east,x_10,y_10 +``` + +**Why:** Each overlay needs its own `fl_layer_apply` component. + +## Background Color Issues + +### Issue: Background Not Applied in Chained Transformations +❌ **Wrong:** +``` +e_background_removal/b_lightblue/e_trim +``` + +✅ **Correct:** +``` +e_background_removal/b_lightblue,c_pad,w_1.0/e_trim +``` + +**Why:** When chaining transformations, use background as a qualifier with a pad crop that doesn't change dimensions. + +### Issue: Background on Non-Transparent Image +❌ **Wrong:** +``` +c_fill,h_400,w_600/b_blue +``` + +✅ **Correct:** +``` +c_pad,b_blue,h_400,w_600 +``` + +**Why:** Background color only shows on transparent areas or with pad crop mode. + +## Border and Rounding Issues + +### Issue: Border Not Following Rounded Corners +❌ **Wrong:** +``` +r_20/bo_5px_solid_blue +``` + +✅ **Correct:** +``` +bo_5px_solid_blue,r_20 +``` + +**Why:** Border is a qualifier in this case and should be in the same component as radius to follow the rounded corners. + +### Issue: Border on Transparent Images +❌ **Wrong:** +``` +bo_5px_solid_blue +``` + +✅ **Correct:** +``` +co_rgb:0066ff,e_outline:outer:15:200 +``` + +**Why:** For images with transparency, use `e_outline` effect instead of `bo_` border. + +## Variable Issues + +### Issue: Variable Name with Underscore +❌ **Wrong:** +``` +$my_width_300/c_scale,w_$my_width +``` + +✅ **Correct:** +``` +$mywidth_300/c_scale,w_$mywidth +``` + +**Why:** Variable names cannot contain underscores. Use alphanumeric characters only, must start with a letter. + +### Issue: String Variable Without Delimiters +❌ **Wrong:** +``` +$color_blue/b_$color +``` + +✅ **Correct:** +``` +$color_!blue!/b_$color +``` + +**Why:** String values must be wrapped in `!` delimiters when assigning to variables. + +### Issue: Variable Reference in Text +❌ **Wrong:** +``` +$date_25/l_text:Arial_40:Day%20$date/fl_layer_apply +``` + +✅ **Correct:** +``` +$date_25/l_text:Arial_40:Day%20$(date)/fl_layer_apply +``` + +**Why:** In text overlays, wrap variable names in `$()` for proper interpolation. + +## Conditional Issues + +### Issue: Missing if_end +❌ **Wrong:** +``` +if_w_gt_300/c_scale,w_300 +``` + +✅ **Correct:** +``` +if_w_gt_300/c_scale,w_300/if_end +``` + +**Why:** Every conditional must close with `if_end`. + +### Issue: Tag Condition Without Delimiters +❌ **Wrong:** +``` +if_sale_in_tags/l_badge/fl_layer_apply/if_end +``` + +✅ **Correct:** +``` +if_!sale!_in_tags/l_badge/fl_layer_apply/if_end +``` + +**Why:** Tag values must be wrapped in `!` delimiters. + +### Issue: Multiple Tags Without Colon +❌ **Wrong:** +``` +if_!sale!_!featured!_in_tags +``` + +✅ **Correct:** +``` +if_!sale:featured!_in_tags +``` + +**Why:** Multiple tags are separated by colons within the `!` delimiters (colon means AND). + +## Text Overlay Issues + +### Issue: Spaces Not Encoded +❌ **Wrong:** +``` +l_text:Arial_40:Hello World/fl_layer_apply +``` + +✅ **Correct:** +``` +l_text:Arial_40:Hello%20World/fl_layer_apply +``` + +**Why:** Text must be URL-encoded. Spaces become `%20`. + +### Issue: Color Not Applied to Text +❌ **Wrong:** +``` +l_text:Arial_40:Hello/co_yellow/fl_layer_apply +``` + +✅ **Correct:** +``` +co_yellow,l_text:Arial_40:Hello/fl_layer_apply +``` + +**Why:** Color (`co_`) is a qualifier and must be in the same component as the text overlay. + +### Issue: Background Not Applied to Text +❌ **Wrong:** +``` +l_text:Arial_40:Hello/b_black/fl_layer_apply +``` + +✅ **Correct:** +``` +b_black,l_text:Arial_40:Hello/fl_layer_apply +``` + +**Why:** Background (`b_`) is a qualifier and must be in the same component as the text overlay. + +## Action vs Qualifier Issues + +### Issue: Multiple Actions in One Component +❌ **Wrong:** +``` +c_scale,e_sepia,w_400 +``` + +✅ **Correct:** +``` +c_scale,w_400/e_sepia +``` + +**Why:** Only one action parameter per component. Separate actions with `/`. + +### Issue: Qualifier in Wrong Component +❌ **Wrong:** +``` +e_colorize:40/co_rgb:0044ff +``` + +✅ **Correct:** +``` +co_rgb:0044ff,e_colorize:40 +``` + +**Why:** Qualifiers must be in the same component as the action they modify. + +## Aspect Ratio Issues + +### Issue: Both Dimensions with c_scale +❌ **Wrong:** +``` +c_scale,h_300,w_400 +``` + +✅ **Correct:** +``` +c_scale,w_400 +``` +or +``` +c_fill,h_300,w_400 +``` + +**Why:** Using both dimensions with `c_scale` distorts the image. Specify one dimension, or use `c_fill` to crop. + +### Issue: Aspect Ratio Syntax +❌ **Wrong:** +``` +c_fill,ar_16/9,w_800 +``` + +✅ **Correct:** +``` +c_fill,ar_16:9,w_800 +``` + +**Why:** Aspect ratio uses colon (`:`) not slash (`/`). + +## Format Issues + +### Issue: PNG for Large Images +❌ **Wrong:** +``` +c_scale,w_2000/f_png +``` + +✅ **Correct:** +``` +c_scale,w_2000/f_auto/q_auto +``` + +**Why:** PNG creates very large files. Use `f_auto` to let Cloudinary choose the best format. + +### Issue: Transparency Lost +❌ **Wrong:** +``` +e_background_removal/f_jpg +``` + +✅ **Correct:** +``` +e_background_removal/f_png +``` + +**Why:** JPEG doesn't support transparency. Use PNG, WebP, or `f_auto`. + +## Quality Issues + +### Issue: Over-Compression +❌ **Wrong:** +``` +q_auto:eco +``` + +✅ **Correct:** +``` +q_auto +``` +or +``` +q_80 +``` + +**Why:** `q_auto:eco` is very aggressive. Use standard `q_auto` or specify quality level. + +### Issue: Large File Size +❌ **Wrong:** +``` +c_scale,w_2000/f_png +``` + +✅ **Correct:** +``` +c_scale,w_2000/f_auto/q_auto +``` + +**Why:** Always use `f_auto/q_auto` for optimization unless specific format required. + +## URL Structure Issues + +### Issue: Missing Asset Type +❌ **Wrong:** +``` +https://res.cloudinary.com/demo/upload/c_scale,w_300/sample.jpg +``` + +✅ **Correct:** +``` +https://res.cloudinary.com/demo/image/upload/c_scale,w_300/sample.jpg +``` + +**Why:** The asset type (`/image/`, `/video/`, or `/raw/`) is required between the cloud name and delivery type. + +**URL structure must be:** +``` +https://res.cloudinary.com///// +``` + +### Issue: Wrong Asset Type +❌ **Wrong if there is no video with public ID `sample`:** +``` +https://res.cloudinary.com/demo/video/upload/sample.jpg +``` + +✅ **Correct for an image with public ID `sample`:** +``` +https://res.cloudinary.com/demo/image/upload/sample.jpg +``` + +**Why:** Asset type must match the type of the uploaded asset. Images use `/image/`, videos use `/video/`, other files use `/raw/`. + +If there is a video with public ID `sample` then `https://res.cloudinary.com/demo/video/upload/sample.jpg` is the correct way to deliver an image thumbnail from the video. + +## Debugging Workflow + +When a transformation doesn't work: + +1. **Verify URL structure** + - Check cloud name exists: `//` + - **Check asset type is present:** `/image/` or `/video/` or `/raw/` + - Check delivery type: `/upload/` or `/fetch/` etc. + - Verify public ID exists and is spelled correctly + +2. **Check component separation** + - Commas within components: `c_scale,w_400` + - Slashes between components: `c_scale,w_400/f_auto/q_auto` + +3. **Validate parameter names** + - Cross-reference with [Transformation Reference](https://cloudinary.com/documentation/transformation_reference.md?install_source=skillspack&referrer=trans-skill) + - Check for typos and abbreviations + +4. **Check action vs qualifier** + - Only one action per component + - Qualifiers in same component as action + +5. **Verify gravity compatibility** + - `g_auto` only works with certain crop modes + - Check crop mode compatibility + +6. **Test incrementally** + - Start with basic transformation + - Add parameters one at a time + - Identify which parameter causes the issue + +7. **Check browser console** + - Look for 404 errors (asset not found) + - Look for 400 errors (invalid transformation) + +8. **Use Cloudinary Media Inspector** + - Install browser extension + - Inspect transformation details + - View transformation breakdown + +## Common Error Messages + +### "Invalid transformation" +- Check parameter names against documentation +- Verify component structure (commas vs slashes) +- Check for typos + +### "Resource not found" +- Verify public ID is correct +- Check asset type (image/video/raw) +- Verify delivery type (upload/fetch/etc) + +### "Invalid crop mode" +- Check crop mode compatibility with other parameters +- Verify `g_auto` is used with compatible crop mode + +### "Invalid color" +- Use `rgb:` prefix for hex colors: `rgb:ff6600` +- Check named color spelling +- Verify color format + +## Testing Tips + +1. **Start simple**: Begin with `c_scale,w_400/f_auto/q_auto` +2. **Add incrementally**: Add one parameter at a time +3. **Use browser DevTools**: Check network tab for errors +4. **Test in isolation**: Remove other transformations to isolate issue +5. **Check documentation**: Always verify parameter syntax + +## Quick Reference + +**Always separate with `/`:** +- Different actions: `c_scale,w_400/e_sepia/f_auto/q_auto` + +**Always in same component:** +- Action and its qualifiers: `co_yellow,l_text:Arial_40:Hello` +- Border and radius: `bo_5px_solid_blue,r_20` + +**Always use:** +- Crop mode with dimensions: `c_scale,w_400` +- `fl_layer_apply` after overlays +- `if_end` after conditionals + +**Never do:** +- `g_auto` with `c_scale`, `c_fit`, `c_limit`, `c_pad` +- Multiple actions in one component +- Underscores in variable names diff --git a/templates/skills/cloudinary-transformations/references/examples.md b/templates/skills/cloudinary-transformations/references/examples.md new file mode 100644 index 0000000..ea8a8c9 --- /dev/null +++ b/templates/skills/cloudinary-transformations/references/examples.md @@ -0,0 +1,712 @@ +# Cloudinary Transformation Examples + +Complete examples of common transformation patterns with explanations. + +## Basic Resizing + +### Scale by Width (Maintain Aspect Ratio) +``` +c_scale,w_400 +``` +Resizes to 400px wide, height adjusts automatically. + +### Scale by Height (Maintain Aspect Ratio) +``` +c_scale,h_300 +``` +Resizes to 300px tall, width adjusts automatically. + +### Fill Exact Dimensions +``` +c_fill,g_auto,h_300,w_400 +``` +Crops and resizes to exactly 400x300, focusing on the most interesting part. + +### Fit Within Dimensions +``` +c_fit,h_300,w_400 +``` +Fits entire image within 400x300 box without cropping. + +### Limit Maximum Size +``` +c_limit,w_1000 +``` +Only scales down if larger than 1000px, never upscales. + +## Smart Cropping + +### Auto Crop with Face Detection +``` +c_fill,g_face,h_200,w_200 +``` +Creates 200x200 thumbnail centered on detected face. + +### Auto Crop to Interesting Content +``` +c_auto,g_auto,h_400,w_600 +``` +Automatically crops to the most interesting part of the image. + +### Thumbnail with Multiple Faces +``` +c_thumb,g_faces,h_150,w_150 +``` +Creates thumbnail including all detected faces. + +## Optimization + +### Basic Optimization +``` +f_auto/q_auto +``` +Automatically selects best format (WebP, AVIF, etc.) and quality. + +### High-Quality Optimization +``` +f_auto/q_auto:best +``` +Higher quality automatic optimization. + +### Economy Optimization +``` +f_auto/q_auto:eco +``` +More aggressive compression for smaller files. + +### Retina Display +``` +c_scale,w_400/f_auto/q_auto/dpr_auto +``` +Automatically serves 2x or 3x resolution for high-DPI displays. + +**Note:** `dpr_auto` only works on Chromium-based browsers (Chrome, Edge, Opera, Samsung Internet) with Client Hints enabled. Falls back to `dpr_1.0` otherwise. For broader browser support, consider using explicit DPR values (e.g., `dpr_2.0`) or JavaScript-based responsive solutions. + +## Effects + +### Grayscale +``` +e_grayscale/f_auto/q_auto +``` + +### Sepia Tone +``` +e_sepia/f_auto/q_auto +``` + +### Blur +``` +e_blur:800/f_auto/q_auto +``` +Blur strength from 1-2000. + +### Sharpen +``` +e_sharpen:100/f_auto/q_auto +``` + +### Cartoonify +``` +e_cartoonify/f_auto/q_auto +``` + +### Pixelate Faces +``` +e_pixelate_faces:20/f_auto/q_auto +``` + +### Background Removal +``` +e_background_removal/f_png +``` +Removes background, use PNG to preserve transparency. + +### Colorize +``` +co_rgb:0044ff,e_colorize:40/f_auto/q_auto +``` +Colorize with blue at 40% strength. Note: `co_` is a qualifier. + +## Overlays + +### Simple Logo Overlay +``` +l_logo/c_scale,w_100/fl_layer_apply,g_north_west,x_10,y_10/f_auto/q_auto +``` +Places 100px wide logo in top-left corner with 10px margins. + +### Semi-Transparent Watermark +``` +l_watermark/c_scale,fl_relative,o_40,w_0.25/fl_layer_apply,g_south_east,x_20,y_20/f_auto/q_auto +``` +Places watermark at 25% of image width, 40% opacity, bottom-right with 20px margins. + +### Text Overlay +``` +co_white,l_text:Arial_60_bold:Hello%20World/fl_layer_apply,g_center/f_auto/q_auto +``` +White text, 60px Arial Bold, centered. + +### Text with Background +``` +b_black,co_white,l_text:Arial_40:Sale/fl_layer_apply,g_north,y_50/f_auto/q_auto +``` +White text on black background at top. + +### Multiple Overlays +``` +l_logo/c_scale,w_80/fl_layer_apply,g_north_west,x_10,y_10/l_badge/c_scale,w_60/fl_layer_apply,g_north_east,x_10,y_10/f_auto/q_auto +``` +Logo in top-left, badge in top-right. + +## Borders & Shapes + +### Rounded Corners +``` +c_fill,h_400,w_600/r_20/f_auto/q_auto +``` +20px rounded corners. + +### Circle +``` +c_fill,h_300,w_300/r_max/f_auto/q_auto +``` +Perfect circle (requires square dimensions). + +### Border +``` +bo_5px_solid_black/f_auto/q_auto +``` +5px solid black border. + +### Border with Rounded Corners +``` +c_fill,h_400,w_600/bo_5px_solid_rgb:0066ff,r_20/f_png/q_auto +``` +Blue border following rounded corners. Note: border and radius in same component. + +### Outline for Transparent Images +``` +co_rgb:0066ff,e_outline:outer:15:200/f_png +``` +15px blue outline at 200 opacity for images with transparency. + +## Background Colors + +### Pad with Background +``` +c_pad,b_lightblue,h_400,w_600/f_auto/q_auto +``` +Pads image to 600x400 with light blue background. + +### Background After Removal +``` +e_background_removal/b_lightblue,c_pad,w_1.0/f_png +``` +Removes background, then adds light blue. Note: background as qualifier with pad. + +### Named Colors +``` +c_pad,b_white,h_400,w_600/f_auto/q_auto +``` +Common named colors: white, black, red, blue, green, yellow, etc. + +### RGB Colors +``` +c_pad,b_rgb:ff6600,h_400,w_600/f_auto/q_auto +``` +Custom RGB color. + +## Rotation & Flips + +### Rotate 90 Degrees +``` +a_90/f_auto/q_auto +``` + +### Rotate Custom Angle +``` +a_-15/f_auto/q_auto +``` +Rotates -15 degrees. + +### Horizontal Flip +``` +a_hflip/f_auto/q_auto +``` + +### Vertical Flip +``` +a_vflip/f_auto/q_auto +``` + +### Rotate and Crop +``` +a_45/c_fill,h_400,w_600/f_auto/q_auto +``` +Rotates first, then crops to dimensions. + +## Variables + +### Square Dimensions +``` +$size_300/c_fill,h_$size,w_$size/r_max/f_auto/q_auto +``` +Creates 300x300 circle using variable. + +### Reusable Color +``` +$brand_!0066ff!/bo_5px_solid_rgb:$brand,c_fill,h_400,w_600/co_rgb:$brand,l_text:Arial_40:Brand/fl_layer_apply,g_south/f_auto/q_auto +``` +Uses brand color for border and text. + +### Template with Multiple Variables +``` +$width_800,$height_600,$color_!blue!/b_$color,c_pad,h_$height,w_$width/f_auto/q_auto +``` +Template for padded images with custom dimensions and color. + +### Date Variable in Text +``` +$date_25/co_white,l_text:Arial_60:Day%20$(date)/fl_layer_apply,g_center/f_auto/q_auto +``` +Displays "Day 25" using variable. + +## Conditionals + +### Resize Large Images Only +``` +if_w_gt_1000/c_scale,w_1000/if_end/f_auto/q_auto +``` +Only resizes if width exceeds 1000px. + +### Different Crop for Portrait vs Landscape +``` +if_ar_gt_1.0/c_fill,h_400,w_600/if_else/c_fill,h_600,w_400/if_end/f_auto/q_auto +``` +Landscape gets 600x400, portrait gets 400x600. + +### Add Badge to Sale Items +``` +if_!sale!_in_tags/l_sale_badge/c_scale,w_100/fl_layer_apply,g_north_east,x_10,y_10/if_end/f_auto/q_auto +``` +Only adds sale badge if "sale" tag exists. + +### Quality Based on Dimensions +``` +if_w_gt_2000/q_90/if_else/q_auto/if_end/f_auto +``` +Higher quality for large images. + +### Multiple Conditions +``` +if_w_gt_800_and_h_gt_600/c_fill,h_600,w_800/if_else/c_fit,h_600,w_800/if_end/f_auto/q_auto +``` +Fill if large enough, otherwise fit. + +## Complex Chained Transformations + +### Avatar Pipeline +``` +c_thumb,g_face,h_400,w_400/e_improve/r_max/bo_3px_solid_white/f_auto/q_auto +``` +1. Crop to face (400x400) +2. Enhance quality +3. Make circular +4. Add white border +5. Optimize + +### Product Image Pipeline +``` +e_background_removal/c_pad,b_white,h_800,w_800/l_watermark/c_scale,fl_relative,o_30,w_0.2/fl_layer_apply,g_south_east,x_30,y_30/f_auto/q_auto +``` +1. Remove background +2. Pad to 800x800 with white +3. Add watermark (20% width, 30% opacity) +4. Position bottom-right +5. Optimize + +### Social Media Post +``` +c_fill,g_auto,h_630,w_1200/co_white,l_text:Arial_80_bold:Breaking%20News/b_black,fl_layer_apply,g_north,y_50/co_yellow,l_text:Arial_40:Read%20More/fl_layer_apply,g_south,y_50/f_auto/q_auto +``` +1. Crop to 1200x630 (Facebook/Twitter size) +2. Add bold white heading on black at top +3. Add yellow call-to-action at bottom +4. Optimize + +### Before/After Comparison +``` +c_fill,h_400,w_300/l_same_image/c_fill,e_grayscale,h_400,w_300/fl_layer_apply,g_west,x_300/f_auto/q_auto +``` +Creates a true side-by-side comparison (600×400) with a grayscale version. Offset the overlay past the base edge to make the canvas auto-expand — set `x_` for horizontal (or `y_` to stack vertically). + +## Video Transformations + +### Video Thumbnail +``` +c_fill,g_auto,h_360,w_640/f_jpg/q_auto +``` +Extracts frame as thumbnail. + +### Video at Specific Time +``` +c_fill,g_auto,h_360,so_5.0,w_640/f_jpg/q_auto +``` +Thumbnail from 5 seconds in (`so_` = start offset). + +### Video Resize +``` +c_scale,w_720/f_auto/q_auto +``` +Resizes video to 720px wide. + +### Video with Overlay +``` +l_logo/c_scale,w_100/fl_layer_apply,g_north_west,x_10,y_10/f_auto/q_auto +``` +Adds logo throughout video. + +## Responsive Images + +### Automatic Breakpoints +``` +c_fill,g_auto,w_auto:breakpoints/f_auto/q_auto/dpr_auto +``` +Cloudinary generates optimal breakpoints. + +**Note:** Both `w_auto` and `dpr_auto` require Client Hints and only work on Chromium-based browsers. Without Client Hints support, `w_auto` is ignored and `dpr_auto` falls back to `dpr_1.0`. + +### Specific Breakpoints +``` +c_fill,g_auto,w_auto:100:1600:80/f_auto/q_auto +``` +Breakpoints from 100px to 1600px in 80px increments. + +**Note:** `w_auto` requires Client Hints and only works on Chromium-based browsers. + +### Art Direction +``` +if_ar_gt_1.5/c_fill,h_400,w_800/if_else/c_fill,h_800,w_400/if_end/f_auto/q_auto +``` +Different crops for different aspect ratios. + +## Advanced Patterns + +### Dynamic Text from Metadata +``` +$title_!md:title!/co_white,l_text:Arial_50:$(title)/fl_layer_apply,g_north,y_30/f_auto/q_auto +``` +Overlays text from asset metadata. + +### Conditional Watermark +``` +if_!premium!_nin_tags/l_watermark/c_scale,fl_relative,o_50,w_0.3/fl_layer_apply,g_center/if_end/f_auto/q_auto +``` +Only watermarks non-premium images. + +### Smart Crop with Fallback +``` +c_fill,g_auto:subject,h_400,w_600/f_auto/q_auto +``` +Tries to detect main subject, falls back to general auto. + +### Aspect Ratio Preservation +``` +c_fill,ar_16:9,w_800/f_auto/q_auto +``` +Maintains 16:9 aspect ratio at 800px wide. + +### Named Transformation +``` +t_thumbnail/f_auto/q_auto +``` +References a named transformation that's been defined for this product environment. + +## Additional Crop Modes + +### Limit Fill (c_lfill) +``` +c_lfill,g_auto,h_400,w_600/f_auto/q_auto +``` +Same as fill but only scales down, never upscales. + +### Fill with Padding (c_fill_pad) +``` +c_fill_pad,g_auto,h_400,w_600/f_auto/q_auto +``` +Fills dimensions with smart crop, adds padding if needed. Requires `g_auto`. + +### Auto with Padding (c_auto_pad) +``` +c_auto_pad,g_auto,h_400,w_600/f_auto/q_auto +``` +Automatically determines best crop, adds padding if needed. Requires `g_auto`. + +### Minimum Fit (c_mfit) +``` +c_mfit,h_400,w_600/f_auto/q_auto +``` +Scales up only (opposite of c_limit). + +### Imagga Smart Crop +``` +c_imagga_crop,g_auto,h_400,w_600/f_auto/q_auto +``` +Uses Imagga's smart cropping algorithm. + +## Advanced Gravity Options + +### Advanced Eyes Detection +``` +c_fill,g_adv_eyes,h_300,w_300/f_auto/q_auto +``` +Focuses on eyes for precise face cropping. + +### Multiple Faces +``` +c_fill,g_faces,h_400,w_600/f_auto/q_auto +``` +Includes all detected faces in the crop. + +### XY Center with Offsets +``` +c_crop,g_xy_center,h_400,w_600,x_100,y_50/f_auto/q_auto +``` +Centers crop at specific coordinates with offsets. + +## Flags and Special Options + +### Progressive Loading +``` +c_scale,w_800/fl_progressive/f_jpg/q_auto +``` +Delivers progressive JPEG for better perceived loading. + +### Lossy Conversion +``` +c_scale,w_800/fl_lossy/f_png/q_auto +``` +Delivers lossy PNG for smaller file size. + +### Force Download +``` +c_scale,w_800/fl_attachment:my-image/f_auto/q_auto +``` +Forces browser to download instead of display. + +### Preserve Transparency +``` +c_scale,w_800/fl_preserve_transparency/f_png +``` +Ensures transparency is maintained during transformations. + +### No Overflow +``` +c_scale,w_2000/fl_no_overflow/f_auto/q_auto +``` +Prevents upscaling beyond original dimensions. + +### Immutable Cache +``` +c_scale,w_800/fl_immutable_cache/f_auto/q_auto +``` +Enables aggressive CDN caching. + +### Region Relative Overlays +``` +c_crop,h_400,w_600/l_badge/c_scale,fl_region_relative,w_0.3/fl_layer_apply,g_north_east/f_auto/q_auto +``` +Sizes overlay relative to cropped region, not original image. + +## Arithmetic Transformations + +### Division +``` +c_scale,w_div_2/f_auto/q_auto +``` +Divides width by 2. + +### Multiplication +``` +c_scale,w_mul_1.5/f_auto/q_auto +``` +Multiplies width by 1.5. + +### Addition +``` +c_crop,h_add_100,w_800/f_auto/q_auto +``` +Adds 100 pixels to height. + +### Subtraction +``` +c_crop,h_sub_50,w_800/f_auto/q_auto +``` +Subtracts 50 pixels from height. + +### Using Initial Dimensions +``` +c_scale,w_iw_div_2/f_auto/q_auto +``` +Sets width to half of initial width (`iw` = initial width). + +### Aspect Ratio Calculations +``` +c_scale,w_800,h_800_div_ar/f_auto/q_auto +``` +Calculates height based on aspect ratio. + +## Context and Metadata Conditionals + +### Context-Based Conditional +``` +if_ctx:!category!_eq_!featured!/l_featured_badge/fl_layer_apply,g_north_east/if_end/f_auto/q_auto +``` +Adds badge if context category equals "featured". + +### Metadata Range Conditional +``` +if_md:!price!_gt_100/l_premium_badge/fl_layer_apply,g_north_west/if_end/f_auto/q_auto +``` +Adds premium badge if metadata price > 100. + +### Multiple Metadata Conditions +``` +if_md:!stock!_gt_0_and_md:!featured!_eq_!true!/e_saturation:50/if_end/f_auto/q_auto +``` +Increases saturation if in stock AND featured. + +## Advanced Text Overlays + +### Text with Stroke +``` +co_white,l_text:Arial_60_bold_stroke:Hello/fl_layer_apply,g_center/f_auto/q_auto +``` +White text with stroke outline. + +### Text with Letter Spacing +``` +co_black,l_text:Arial_40_letter_spacing_10:SPACED/fl_layer_apply,g_center/f_auto/q_auto +``` +Text with 10px letter spacing. + +### Text with Line Spacing +``` +co_black,l_text:Arial_40_line_spacing_20:Line%20One%0ALine%20Two/fl_layer_apply,g_center/f_auto/q_auto +``` +Multi-line text with custom line spacing. + +### Text with Border +``` +bo_5px_solid_black,co_white,l_text:Arial_50:Bordered/fl_layer_apply,g_center/f_auto/q_auto +``` +Text with border. + +## Advanced Color Transformations + +### Replace Color +``` +e_replace_color:blue:50:white/f_auto/q_auto +``` +Replaces blue colors (within 50 tolerance) with white. + +### Tint +``` +co_rgb:ff0000,e_tint:50/f_auto/q_auto +``` +Applies 50% red tint. + +### Contrast and Brightness +``` +e_brightness:30/e_contrast:20/f_auto/q_auto +``` +Increases brightness by 30 and contrast by 20. + +### Saturation +``` +e_saturation:50/f_auto/q_auto +``` +Increases saturation by 50. + +### Hue Shift +``` +e_hue:40/f_auto/q_auto +``` +Shifts hue by 40 degrees. + +## Generative AI Examples + +### Generative Fill +``` +c_pad,ar_16:9,b_gen_fill,w_1200/f_auto/q_auto +``` +Uses AI to fill padded areas with generated content. + +### Generative Replace +``` +e_gen_replace:from_dog;to_cat/f_auto/q_auto +``` +Replaces dogs with cats using AI. + +### Generative Restore +``` +e_gen_restore/f_auto/q_auto +``` +Restores and enhances old or low-quality images. + +### Generative Recolor +``` +e_gen_recolor:prompt_golden%20hour%20lighting/f_auto/q_auto +``` +Recolors image based on text prompt. + +## Quality Variations + +### Quality with Chroma Subsampling +``` +c_scale,w_800/f_jpg/q_80:420 +``` +JPEG quality 80 with 4:2:0 chroma subsampling. + +### Quality Range +``` +c_scale,w_800/f_auto/q_auto:low +``` +Automatic quality with low setting for smaller files. + +## DPR and Responsive + +**Important:** `dpr_auto` and `w_auto` parameters only work on Chromium-based browsers (Chrome, Edge, Opera, Samsung Internet) with Client Hints enabled. They do NOT work inside named transformations. For broader browser support, see the [Responsive Images documentation](https://cloudinary.com/documentation/responsive_images.md?install_source=skillspack&referrer=trans-skill). + +### Specific DPR +``` +c_scale,w_400/dpr_2.0/f_auto/q_auto +``` +Delivers 800px image for 2x displays. Explicit DPR values work in all browsers. + +### Auto Breakpoints +``` +c_fill,g_auto,w_auto:breakpoints/f_auto/q_auto +``` +Cloudinary generates optimal responsive breakpoints. Requires Client Hints support. + +### Breakpoints with Range +``` +c_fill,g_auto,w_auto:100:1600:80/f_auto/q_auto +``` +Breakpoints from 100px to 1600px in 80px steps. Requires Client Hints support. + +## Fetch Delivery Type + +### Fetch Remote Image +``` +https://res.cloudinary.com/demo/image/fetch/c_scale,w_400/f_auto/q_auto/https://example.com/image.jpg +``` +Fetches and transforms remote image. + +### Fetch with Signature +``` +https://res.cloudinary.com/demo/image/fetch/s--signature--/c_scale,w_400/f_auto/q_auto/https://example.com/image.jpg +``` +Fetches remote image with signed URL for security. diff --git a/templates/skills/cloudinary-transformations/references/named-transformations.md b/templates/skills/cloudinary-transformations/references/named-transformations.md new file mode 100644 index 0000000..ed5fc9e --- /dev/null +++ b/templates/skills/cloudinary-transformations/references/named-transformations.md @@ -0,0 +1,145 @@ +# Named Transformations + +Named transformations allow you to save transformation chains with a name (e.g., `t_thumbnail`) and reuse them across your application. + +## When to Suggest Named Transformations + +- **Transformations used across multiple assets** - Consistency and easy updates +- **Complex transformation chains** - Easier to maintain and read +- **Saving money on expensive transformations** - Named transformations are required for baseline transformations, which save processing time and cost by avoiding regeneration of shared transformation steps. + +## Example + +``` +# Instead of repeating the same transformation: +❌ c_thumb,g_face,h_200,w_200/r_max/e_sharpen/f_auto/q_auto + +# Create named transformation "avatar": +✅ t_avatar/f_auto/q_auto +``` + +## How to Reference Named Transformations + +``` +t_ # Use named transformation +t_/c_scale,w_500 # Named transformation + additional changes +c_fill,w_300/t_ # Transform first, then apply named transformation +``` + +## Limitations of Named Transformations + +**Automatic parameters don't work inside named transformations:** +- ❌ `f_auto` - Automatic format selection +- ❌ `dpr_auto` - Automatic DPR matching +- ❌ `w_auto` - Automatic width matching (with Client Hints) + +These parameters rely on runtime information from the client or CDN that isn't available when the named transformation is processed. Use them directly in the URL instead: + +``` +# ❌ Don't do this: +t_product_thumb # where product_thumb includes f_auto + +# ✅ Do this instead: +t_product_thumb/f_auto/q_auto +``` + +See [Limitations of named transformations](https://cloudinary.com/documentation/image_transformations.md?install_source=skillspack&referrer=trans-skill#limitations_of_named_transformations) for complete details. + +## Baseline Transformations + +Baseline transformations (`bl_`) cache the result of a named transformation so it doesn't have to be regenerated when combined with other transformations. This saves processing time and cost. + +### When to Use Baseline Transformations + +**Especially useful for:** +- **Expensive AI transformations** (background removal, generative AI, upscaling) - Avoid re-processing +- **Time-consuming operations** that you'll apply variations to +- **Transformations with special transformation counts** (75-230 tx) that you need to reuse + +**Consider eagerly generating baselines:** +- On upload using the [upload method](https://cloudinary.com/documentation/image_upload_api_reference.md?install_source=skillspack&referrer=trans-skill#upload_method) or [upload preset](https://cloudinary.com/documentation/upload_presets.md?install_source=skillspack&referrer=trans-skill) +- For existing assets using the [explicit method](https://cloudinary.com/documentation/image_upload_api_reference.md?install_source=skillspack&referrer=trans-skill#explicit_method) + +### Syntax + +``` +bl_/ +``` + +### Examples + +**Example 1: Background removal + grayscale baseline, then add effects** +``` +# Named transformation "bg_rem_gray_jxl" contains: +e_background_removal/f_jxl/q_100/e_grayscale + +# Use as baseline: +bl_bg_rem_gray_jxl/e_cartoonify/f_auto/q_auto +``` +Result: Background removed, grayscale applied once (cached), then cartoonify effect added. + +**Example 2: Same baseline, resize and add underlay** +``` +bl_bg_rem_gray_jxl/c_fill,h_150/u_docs:sky/c_fill,h_150/fl_layer_apply +``` + +**Example 3: Video baseline with trimming** +``` +# Named transformation "first5_rotate" contains: +du_5/f_mp4/a_15 + +# Use as baseline: +bl_first5_rotate/e_loop:2/f_auto/q_auto +``` +Result: Video trimmed to 5 seconds and rotated once (cached), then looped twice. + +### Critical Rules + +1. **Baseline must be the first component** in the transformation chain +2. **Baseline must be the only transformation parameter** in that component + - ✅ `bl_bg_removed/c_scale,w_500` + - ❌ `bl_bg_removed,c_scale,w_500` + +3. **Named transformation must include a format** (`f_`) + - Use a supported format transformation (e.g., `f_jxl`, `f_png`, `f_jpg`) + - Cannot use `f_auto` in the named transformation (but you can use `f_auto` in subsequent components) + +4. **Prevent double lossy encoding** + - Consider using `f_jxl/q_100` in the baseline transformation to avoid quality loss + - JXL is lossless at q_100, preventing degradation from double encoding + +5. **Variables must be defined in the named transformation** if used in the baseline + +6. **Not supported for:** + - Fetched media (`/fetch/`) + - Incoming transformations + +### Cost Savings Example + +Without baseline: +``` +# Every URL regenerates the background removal (75 tx each time) +e_background_removal/c_scale,w_500/f_auto/q_auto # 75 tx +e_background_removal/c_fill,h_300,w_400/f_auto/q_auto # 75 tx +e_background_removal/e_grayscale/f_auto/q_auto # 75 tx +``` + +With baseline: +``` +# Named transformation "bg_removed" contains: e_background_removal/f_jxl/q_100 +# Baseline is generated once, then reused (75 tx only once) +bl_bg_removed/c_scale,w_500/f_auto/q_auto # 1 tx +bl_bg_removed/c_fill,h_300,w_400/f_auto/q_auto # 1 tx +bl_bg_removed/e_grayscale/f_auto/q_auto # 1 tx +``` + +**Total savings**: 225 tx → 78 tx (75 tx for initial baseline + 3 tx for variations) + +For more cost optimization strategies, see [transformation-costs.md](transformation-costs.md) + +## Implementation Note + +Named transformations are created in the Cloudinary Console or via API. When suggesting them to users, explain: +1. The transformation would be saved in their Cloudinary account with a name +2. They can then reference it using `t_` in URLs +3. For expensive operations, they can generate a baseline transformation eagerly or use `bl_` to cache results diff --git a/templates/skills/cloudinary-transformations/references/responsive-images.md b/templates/skills/cloudinary-transformations/references/responsive-images.md new file mode 100644 index 0000000..6518a1c --- /dev/null +++ b/templates/skills/cloudinary-transformations/references/responsive-images.md @@ -0,0 +1,717 @@ +# Responsive Images & Client Hints + +Comprehensive guide to creating responsive images with Cloudinary, including `dpr_auto`, `w_auto`, and Client Hints configuration. + +## Overview + +Cloudinary provides several approaches for responsive images: +1. **Client Hints** (`dpr_auto`, `w_auto`) - Automatic adaptation (Chromium-only) +2. **Explicit DPR values** (`dpr_2.0`) - Universal browser support +3. **JavaScript solutions** - Dynamic responsive images +4. **Responsive breakpoints** (`w_auto:breakpoints`) - Multiple image sizes + +## Device Pixel Ratio (DPR) + +### Understanding DPR + +DPR represents the ratio between physical pixels and CSS pixels on a device: +- **1x displays**: Standard screens (DPR = 1.0) +- **2x displays**: Retina/HiDPI screens (DPR = 2.0) +- **3x displays**: High-end mobile devices (DPR = 3.0) + +**Why it matters:** A 400px wide image needs to be 800px actual size on 2x displays to look sharp. + +### `dpr_auto` Parameter + +**Syntax:** +``` +c_scale,w_400/dpr_auto/f_auto/q_auto +``` + +**What it does:** Automatically multiplies dimensions by the device's DPR +- On 1x display: Delivers 400px image +- On 2x display: Delivers 800px image +- On 3x display: Delivers 1200px image + +### Browser Compatibility + +**✅ Works on Chromium-based browsers:** +- Google Chrome +- Microsoft Edge +- Opera +- Samsung Internet +- Brave + +**❌ Does NOT work on:** +- Firefox +- Safari (macOS and iOS) +- Other non-Chromium browsers + +**Fallback behavior:** When Client Hints unavailable, treats request as `dpr_1.0` + +### Named Transformation Limitation + +`dpr_auto` does NOT work inside named transformations (similar to `f_auto` and `w_auto`). + +**Why:** Client Hints information isn't available when named transformation is processed. The CDN needs to "see" `dpr_auto` directly in the URL to adapt it. + +**❌ Don't do this:** +``` +# Named transformation "product_thumb" contains: c_fill,w_300,h_300/dpr_auto/f_auto +t_product_thumb +``` + +**✅ Do this instead:** +``` +# Named transformation "product_thumb" contains: c_fill,w_300,h_300 +t_product_thumb/dpr_auto/f_auto/q_auto +``` + +## Enabling Client Hints + +Client Hints must be enabled for `dpr_auto` and `w_auto` to work. + +### HTML Configuration + +Add these `` tags to your HTML `` **before** any ``, `