Home / All Skills / Content & Media Creation / canghe-compress-image
Content & Media Creation · freestylefly/canghe-skills

canghe-compress-image

Compresses images to WebP (default) or PNG with automatic tool selection. Use when user asks to "compress image", "optimize image", "convert to webp", or reduce image file size.

L4 High-Privilege · Graded auth & full auditV1 Commit-PinnedExecute CommandWrite FileDual-pass Audit
Author freestyleflyGitHub freestylefly/canghe-skills ↗License MIT(仓库根 LICENSE)Commit dd0bf35595
Control levels describe skill capabilities and suggested control measures; they do not represent quality or safety certifications, nor do they dictate usability. Usage decisions rest entirely with users and administrators. Different agent hosts apply varying constraints; do not assume hosts provide automatic protection. Third-party skill copyrights belong to their original authors. Use at your own risk.

1How It Works & Mechanism

The core logic is "automatically selecting a compressor based on the target format": webp prioritizes cwebp, then ImageMagick's convert, and finally sharp; non-webp formats use sips on macOS, otherwise convert, falling back to sharp.

skills/canghe-compress-image/scripts/main.ts
if (await commandExists("cwebp")) return "cwebp";
What is happening here: detectCompressor decides based on the runtime platform and commands in PATH rather than the npm dependency list—as long as one of cwebp/convert/sips exists, it runs without node_modules.

Availability probing relies on which + child_process.spawn, and the compression itself spawns the system CLI and parses the exit code/stderr.

skills/canghe-compress-image/scripts/main.ts
const proc = spawn("which", [cmd], { stdio: "pipe" });
What is happening here: runCmd uniformly collects stderr, throwing 'sips failed/cwebp failed/convert failed' on non-zero exit codes; error messages originate from the external tools.

sharp serves as a pure JS fallback and is lazily loaded via dynamic import (incurring loading overhead only when preceding paths miss).

skills/canghe-compress-image/scripts/main.ts
const sharp = (await import("sharp")).default;
What is happening here: The three formats route through pipeline.webp/png/jpeg({ quality }) respectively; sharp is the only dependency whose absence will cause execution failure if reached.

Disk writing uses "temporary file + atomic rename": it first writes to output + '.tmp', and renames it to the target name upon success.

skills/canghe-compress-image/scripts/main.ts
renameSync(tempOutput, output);
What is happening here: Prevents incomplete files left behind by midway failures; within the same function, if --keep is not enabled and the input/output names differ, the original image is first renamed to *_original before the new file is saved.

Defaults to "convert rather than save as copy": same directory, same basename, changed extension; outputs {base}-compressed.{ext} only when --keep is enabled and the extension remains identical.

skills/canghe-compress-image/scripts/main.ts
return join(dir, `${base}-compressed${ext}`);
What is happening here: getOutputPath can specify any target path with -o/--output, in which case the original image is not renamed.

When --keep is not enabled, the original image is renamed and preserved as {base}_original.{ext}.

skills/canghe-compress-image/scripts/main.ts
renameSync(absInput, `${base}_original${ext}`);
What is happening here: The original image is not deleted by default (only renamed), but script consumers must be aware that the filename changes.

Directory mode recursively collects files based on an extension whitelist, processes them one by one, and aggregates the total size.

skills/canghe-compress-image/scripts/main.ts
const SUPPORTED_EXTS = [".png", ".jpg", ".jpeg", ".webp", ".gif", ".tiff"];
What is happening here: collectFiles recurses only with -r; single-file failures only log errors without aborting the entire batch, finally reporting the total size reduction.

Preferences are only declared at the SKILL.md layer (resolved via EXTEND.md across three lookup levels and applied if matched); the script itself does not read configuration files.

skills/canghe-compress-image/SKILL.md
Read, parse, apply settings
What is happening here: EXTEND.md supports default format/quality/keeping original images; pure CLI usage behaves identically to invocation via an agent, differing only in that the agent supplements default arguments per preferences.

2Core Capabilities

01Automatic compressor backend selection (four-tier fallback across sips / cwebp / ImageMagick / sharp)
02Format conversion to webp/png/jpeg + quality parameters (0-100, default 80)
03Single file and directory batch processing (-r recursive, extension whitelist)
04Original image retention strategy (-k uses -compressed naming; defaults to renaming original to *_original)
05Atomic disk writing (.tmp staging followed by rename), leaving no half-finished files on failure
06Size comparison reporting + --json structured output
07EXTEND.md preferences (default format/quality/keep original) with three-level path lookup

3External Dependencies

KindDependency / Endpoint
clisips(macOS 系统自带图像工具,非 webp 时的首选)
clicwebp(libwebp 官方 CLI,webp 首选)
cliImageMagick convert
cliwhich(命令可用性探测)
packagesharp(动态 import 的纯 JS 兜底;skill 目录无 package.json,依赖运行环境解析)

4Recommended Governance & Evidence

Suggested Controls for Safe Operation
For Agent Runtime
Graded/per-use authorization, sandbox recommended
For Administrators
Approval workflow, rollback support, full audit
Evidence & Triggers (File Paths & Excerpts)
  • scripts/: Executes local scripts or commands: scripts/main.ts (run via bun; spawns which / sips / cwebp / convert, dynamically imports sharp)
  • 本地工作目录: File I/O and artifact output: Outputs images (same directory with new extension or path specified via -o), temporary file <output>.tmp, renames original image to {base}_original.{ext} when --keep is disabled
Audit Notes: (a) Behavior is completely local: probes via spawned 'which', performs compression calling sips/cwebp/convert with sharp fallback, reads local images and writes local files, zero network endpoints, zero credential reading, zero configuration file parsing (EXTEND.md is read only by the agent). (b) File side effects to be aware of: when --keep is omitted, the script uses renameSync to rename the original image to {base}_original.{ext} before writing the new file, which has a broad impact in batch directory mode; it is recommended to run a small trial first or explicitly designate the output with -o. (c) Relies on one of imagemagick/cwebp/sips/sharp in the runtime environment; fails if neither a CLI tool nor sharp is available. Precedent: local read/write tools such as baoyu-compress-image are classified as blue.

5Second-Pass Verification

  • [ok] 自带脚本只有 scripts/main.ts,且仅本地行为 — 扫描“网络请求”0 命中;唯一执行面是 spawn which/sips/cwebp/convert 与动态 import sharp;无 fetch/http 调用。
  • [ok] 原图改名副作用 — processFile 中当 !keep 且 absInput !== output 时 renameSync 原图为 *_original.{ext};已在 risks 提示,批量前建议试跑或 -o。
  • [ok] sharp 依赖来源(无自带 package.json) — skill 目录确无 package.json;sharp 靠运行环境解析,缺失时仅在前几条 CLI 路径都不命中才会失败。
  • [ok] 选项表与脚本参数一致 — SKILL.md 的 7 个 option 与 parseArgs 处理的分支完全对应,默认值 format=webp、quality=80、keep/recursive/json=false。
  • [ok] 安全面与档位 — 零网络、零凭证、零配置解析;仅本地文件读写与系统 CLI 调用,判 blue 与前例一致。
  • [ok] meta 元数据 — commit dd0bf355…、path skills/canghe-compress-image、license MIT 与 bundle §0 核定值一致。

6Verdict & Scenarios

  • Zero hard npm dependencies; dynamically uses whichever system tool is installed, offering high cross-platform availability.
  • Atomic disk writing + batch fault tolerance; batch compression will not be interrupted by single-file failures.
  • Small parameter surface with high consistency between documentation and implementation, ensuring predictable behavior.
  • Clean security profile: strictly local, zero network access, zero credentials.
  • Best for: Suitable for writers, frontend developers, or content engineers who need to batch-convert images to WebP or compress them to reduce file size with zero-dependency quick onboarding.
    Not for: Not suitable for professional imaging pipelines requiring fine-grained lossless or lossy quality control (such as custom encoding parameters); not suitable for automation scripts that require preserving original filenames (they are renamed by default).
    Install Agent-Ready
    ① Verified Mirror 2026-10-10
    Option A · Direct DownloadDownload canghe-compress-image.tar.gz
    sha256: 346c02cfdb2597bb…
    Option B · Copy Guide for Agent
    install.json
    Agents automatically download and verify mirrors from this JSON guide.
    ② Upstream GitHub
    GitHub Repo ↗
    Pinned to commit dd0bf35595.