---
name: image-format-detector-yashu
description: 判断用户输入的图片文件路径对应的真实格式（JPG/PNG/WebP），通过读取文件头魔数识别，不依赖文件扩展名。激活条件：用户消息须包含以下关键词之一:`判断图片格式`、`识别图片类型`、`图片格式检测`、`检测图片是jpg还是png`、`检测图片是png还是webp`。
metadata:
  author: "AI"
  updated: "2026-08-02 21:57:00"
  version: "1.0.0"
title: image-format-detector-yashu
canonical_url: https://skilld.dev/gh/steelan9199/wechat-publisher/image-format-detector-yashu
last_updated: 2026-10-07T07:20:50.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> If the user asked to install this Skill, run `npx skilld install steelan9199/wechat-publisher/image-format-detector-yashu`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/image-format-detector-yashu`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/steelan9199/wechat-publisher/image-format-detector-yashu) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/image-format-detector-yashu`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/image-format-detector-yashu --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/image-format-detector-yashu --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# 图片格式检测器

## 功能概述

判断用户输入的文件路径对应的图片真实格式，支持 JPG/JPEG、PNG、WebP 三种格式。通过读取文件头（魔数/Magic Number）识别，不依赖文件扩展名，可检测出扩展名与实际格式不符的情况。

## 环境说明

- 本 Skill 无需脚本，直接通过系统命令读取文件头字节判断格式
- 本 Skill 运行命令时采用**条件执行**（前一条成功才执行下一条），跨平台规则如下：
  - **bash/zsh**（Linux/macOS）：`cmd1 && cmd2`
  - **PowerShell 5**（Windows）：`cmd1; if ($?) { cmd2 }`（PowerShell 5 不支持 `&&`）
  - **PowerShell 7+**：`&&` 和 `; if ($?) { cmd2 }` 均可，为最大兼容性推荐 `; if ($?) { cmd2 }`
  - **禁止单 `&`**：在 bash 中 `&` 表示后台执行，语义完全不同
  - 示例（bash/zsh）：`test -f "$path" && xxd -l 12 -p "$path"`
  - 示例（PowerShell 5）：`Test-Path "$path"; if ($?) { [System.IO.File]::ReadAllBytes("$path")[0..11] }`

## 文件头魔数对照表

| 格式 | 偏移 | 魔数（十六进制）                          | 说明                              |
| ---- | ---- | ----------------------------------------- | --------------------------------- |
| JPG  | 0    | `FF D8 FF`                                | 前 3 字节                         |
| PNG  | 0    | `89 50 4E 47 0D 0A 1A 0A`                 | 前 8 字节（即 ‰PNG\r\n\x1A\n）    |
| WebP | 0    | `52 49 46 46` + 4字节长度 + `57 45 42 50` | 前4字节为 RIFF，偏移 8-11 为 WEBP |

## 执行步骤

| 步骤 | 执行动作         | 具体命令/操作                                                                                                                                                                                                                                                                                             |
| ---- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ---------- | --------------------------------------------------------------------------- |
| 1    | 接收文件路径     | 从用户消息中提取图片文件的绝对路径，记为 `<文件路径>`                                                                                                                                                                                                                                                     |
| 2    | 验证文件存在     | Windows PowerShell：运行 `Test-Path "<文件路径>"`，返回 `True` 即存在<br>Linux/macOS bash：运行 `test -f "<文件路径>" && echo "exists"`                                                                                                                                                                   |
| 3    | 读取文件头12字节 | Windows PowerShell：运行 `$bytes = [System.IO.File]::ReadAllBytes("<文件路径>")[0..11]; $hex = ($bytes                                                                                                                                                                                                    | ForEach-Object { $\_.ToString("X2") }) -join " "; Write-Output $hex`<br>Linux/macOS bash：运行 `xxd -l 12 -p "<文件路径>" | tr -d '\n' | sed 's/\(..\)/\1 /g'`<br>说明：读取前 12 字节足以覆盖所有三种格式的魔数判断 |
| 4    | 判断格式         | 将读取的十六进制字符串（统一转为大写）与【文件头魔数对照表】比对，按以下优先级判断：<br>• 以 `FF D8 FF` 开头 -> 判定为 **JPG/JPEG**<br>• 以 `89 50 4E 47` 开头 -> 判定为 **PNG**<br>• 以 `52 49 46 46` 开头，且偏移 8-11 字节为 `57 45 42 50` -> 判定为 **WebP**<br>• 以上均不匹配 -> 判定为 **未知格式** |
| 5    | 提取扩展名       | 从 `<文件路径>` 中提取文件扩展名（最后一个 `.` 之后的部分，转小写），用于与真实格式比对                                                                                                                                                                                                                   |
| 6    | 输出结果         | 按【输出格式】输出判断结果                                                                                                                                                                                                                                                                                |

## 输出格式

判断完成后，输出以下结构化信息：

```
图片格式检测结果：
- 文件路径：{用户输入的路径}
- 文件扩展名：{从路径提取的扩展名，如 .jpg / .png / .webp / 无扩展名}
- 真实格式：{JPG / PNG / WebP / 未知格式}
- 扩展名是否匹配：{是 / 否}
```

若扩展名与真实格式不符（如 `.jpg` 文件实际为 PNG），需在结果后追加提示：

```
⚠️ 注意：该文件的扩展名（.jpg）与真实格式（PNG）不符，建议修正扩展名或使用支持该格式的工具打开。
```

## 错误处理

| 错误场景   | 错误表现                    | 处理方式                                                                                 |
| ---------- | --------------------------- | ---------------------------------------------------------------------------------------- |
| 文件不存在 | `Test-Path` 返回 `False`    | 中断执行，提示用户"文件路径不存在，请确认路径是否正确"                                   |
| 路径无权限 | 读取文件头报错"拒绝访问"    | 中断执行，提示用户"没有读取该文件的权限，请检查文件权限设置"                             |
| 文件过小   | 文件字节数少于 12           | 读取实际可用字节数进行判断；若不足 3 字节则判定为"未知格式"                              |
| 未知格式   | 文件头不匹配任何已知魔数    | 输出"未知格式"，并附上读取到的文件头十六进制值供用户参考                                 |
| 路径含空格 | 命令解析错误                | 路径须用双引号包裹（PowerShell 和 bash 均适用双引号，bash 中避免用单引号以支持变量展开） |
| 命令不可用 | Linux/macOS 下 `xxd` 未安装 | 回退使用 `od -A x -t x1 -N 12 "<文件路径>"` 命令读取文件头                               |
