Home / All Skills / Workflow & Core Tools / baoyu-compress-image
Workflow & Core Tools · JimLiu/baoyu-skills

baoyu-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 JimLiuGitHub JimLiu/baoyu-skills ↗Stars 25926License MIT(仓库根 LICENSE,Copyright (c) 2026 Jim Liu;GitHub API license.spdx_id=MIT)Commit 1567581c26
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": for webp, it prioritizes cwebp, then ImageMagick's convert, and falls back to sharp; for non-webp, it uses sips directly on macOS, otherwise convert, and falls back to sharp.

skills/baoyu-compress-image/scripts/main.ts
if (await commandExists("cwebp")) return "cwebp";
The criterion is the operating platform and commands available in PATH, rather than the npm dependency list—meaning it can run without node_modules (as long as one of cwebp, convert, or sips is available).

Availability detection relies on which + child_process.spawn; compression itself also spawns system CLIs and parses exit codes/stderr.

skills/baoyu-compress-image/scripts/main.ts
const proc = spawn("which", [cmd], { stdio: "pipe" });
runCmd uniformly collects stderr; a non-zero exit throws 'sips failed/cwebp failed/convert failed', with error details originating from the external tools.

sharp serves as a pure JS fallback and is lazily loaded via dynamic import (the loading cost is incurred only when none of the first three paths match).

skills/baoyu-compress-image/scripts/main.ts
const sharp = (await import("sharp")).default;
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 writes use a "temporary file + atomic rename" pattern: it writes to output + '.tmp' first, then renames to the target filename upon success to avoid leaving incomplete files on mid-run failure.

skills/baoyu-compress-image/scripts/main.ts
renameSync(tempOutput, output);
In the same function, if --keep is not enabled and the input/output filenames differ, it renames the original image to {base}_original{ext} before writing the new file, effectively retaining a copy of the original image by default (just renamed).

Defaults to "convert rather than save as a copy": same directory, same base name, different extension; only outputs {base}-compressed.{ext} when --keep is enabled and the extensions match.

skills/baoyu-compress-image/scripts/main.ts
return join(dir, `${base}-compressed${ext}`);
Used with -o/--output, an arbitrary target path can be specified, in which case the original image is not renamed (renaming occurs only when absInput !== output).

Directory mode recursively collects files based on an extension whitelist, processes them one by one, and aggregates total file size; failure of a single file prints an error without aborting the entire batch.

skills/baoyu-compress-image/scripts/main.ts
const SUPPORTED_EXTS = [".png", ".jpg", ".jpeg", ".webp", ".gif", ".tiff"];
Summary output follows the format 'Processed N files: 12MB → 4.1MB (66% reduction)', and outputs files[] + summary when --json is specified.

Preferences are declared only at the SKILL.md layer (three-tier EXTEND.md lookup, falling back to default format/quality/retention policy if not found); the script itself does not parse configuration files.

skills/baoyu-compress-image/SKILL.md
If none found, use defaults.
Therefore, pure CLI usage behaves identically to invocation via an agent, with the only difference being that the agent populates default parameters based on preferences.

2Core Capabilities

01Automatic compression backend selection (four-tier fallback: sips / cwebp / ImageMagick / sharp)
02Format conversion for webp/png/jpeg + quality parameter (0-100, default 80)
03Single-file and directory batch processing (-r recursive, extension whitelist)
04Original image retention policy (-k uses -compressed naming; defaults to renaming original to *_original)
05Atomic disk writes (staging via .tmp then rename), leaving no partial artifacts on failure
06Size comparison reporting + --json structured output
07EXTEND.md preferences (default format/quality/keep original) with three-tier 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 by -o), temporary files <output>.tmp, renames original to {base}_original.{ext} when --keep is not enabled
Audit Notes: (a) All behavior is entirely local: spawns 'which' for detection, invokes sips/cwebp/convert for compression, uses sharp as fallback, reads local images and writes local files, with zero network endpoints, zero credential access, and zero config file parsing (EXTEND.md is read only by the agent). (b) File side effects to be aware of: when --keep is not enabled, the script renames the original file via renameSync to {base}_original.{ext} before writing the new file, which has a broad impact in batch directory mode; testing on a small scope first or explicitly specifying output via -o is recommended. (c) Depends on at least one of imagemagick/cwebp/sips/sharp in the runtime environment; fails if neither CLIs nor sharp are available. Comparison with precedent: local read/write tools like canvas-design / writing-fragments are classified as blue.

5Second-Pass Verification

  • [ok] 无网络调用 / 无凭证读取 — 全文无 fetch/http/curl/API key/cookie/process.env 命中;唯一子进程是 which 与四个图像 CLI。
  • [ok] “默认覆盖原图”的初判修正 — 第一遍曾疑为删除原图;逐行读后确认为 renameSync(absInput, `${base}_original${ext}`)——原图被改名保留,结论已按此更正写进 risks。
  • [ok] sharp 依赖可解析性 — skill 目录无 package.json;仓库根 dependencies 含 sharp ^0.34.5。非 workspace 环境需自行安装 sharp 或依赖 cwebp/convert/sips 分支。
  • [ok] 四个压缩器的参数与退出码处理 — sips 用 -s format/-s formatOptions/--out;cwebp 用 -q/-o;convert 用 [-quality];sharp 走 pipeline.webp/png/jpeg。均检查 code!==0 并抛错。
  • [ok] 批量容错与汇总 — 目录模式下 processFile 抛错被 catch 后仅 console.error 继续;--json 输出 files[] + summary(compressor/totals/ratio)。
  • [ok] meta 元数据 — GitHub API:MIT、25926 stars、pushed_at 2026-09-10T15:13:43Z;本地 HEAD 与任务 pin 1567581c26ec… 一致。

6Verdict & Scenarios

  • Environment adaptive: Uses whatever is installed (cwebp/ImageMagick/sips/sharp), making it easier to run successfully out of the box compared to solutions strictly requiring sharp.
  • Safe disk writes: Atomic replacement using .tmp + rename leaves no half-written files on failure.
  • Effortless batch processing: Directory -r recursion + whitelist filtering + overall aggregation, ideal for batch image reduction in blogs/documentation sites.
  • Zero network, zero credentials: Requires only local file permissions, making it suitable for egress-sensitive environments.
  • --json output facilitates CI/CD and pipeline integration.
  • Best for: Ideal for automation scenarios such as batch-converting large images to WebP for websites/blogs or reducing deliverable sizes, as well as embedding into agent workflows for post-generation compression steps (can be invoked by other baoyu skills).
    Not for: Not suitable for scenarios requiring fine-grained control over EXIF/ICC preservation or advanced encodings like lossless/AVIF; not suitable for pipelines with strict original filename checks that do not allow renaming.
    Install Agent-Ready
    ① Verified Mirror 2026-09-15
    Option A · Direct DownloadDownload baoyu-compress-image.tar.gz
    sha256: 5c0a427092d20497…
    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 1567581c26.