《游戏编辑器技术原理与架构》4.1 图像解码与格式归一

不加载全图就拿到宽高与通道——头解析是图像导入的第一课。本节手写 PNG 签名 + IHDR、JPEG SOI + SOF 的字节级解析,把两种格式收敛成统一 ImageInfo(宽高、通道、归一格式 rgba8/rgb8/luminance8);6 条用例本机真跑,钉住「非法数据返回 null 不崩溃、签名后非 IHDR 判无效」两条健壮性。

4.1 图像解码与格式归一

图像导入的第一课不是「怎么解压像素」,而是「怎么不加载全图就知道图长什么样」。属性面板要显示尺寸、缩略图要估算面积、加载器要分配缓冲——这些都只需要头信息:格式、宽高、通道数。PNG 的宽高在文件开头 26 个字节内,JPEG 的在一个 marker 段里。本节手写这两段字节解析,把千变万化的格式收敛成一份统一的 ImageInfo。

本节的解析函数:

  • isPng(bytes) / isJpeg(bytes):按签名识别格式。
  • pngInfo(bytes):解析 PNG IHDR——宽高、颜色类型→通道数、格式归一。
  • jpegInfo(bytes):扫描段找 SOF——宽高、组件数。
  • parseImageHeader(bytes):按签名路由,返回统一 ImageInfo 或 null。

本章与站内既有内容的分工

主题站内既有内容本节做什么
导入器框架3.1 导入器注册与分发.png 导入器调用本节的解析器取头信息
导入流水线3.2 导入流水线:阶段与编排头解析是流水线的「read」阶段
资产扫描2.1 扫描与内容哈希扫描只认扩展名;本节从字节确认「真 PNG / 真 JPEG」

签名与 IHDR:PNG 的开场白

PNG 文件以 8 字节签名开头:89 50 4E 47 0D 0A 1A 0A。签名之后是第一个 chunk——IHDR,它里面有宽度(4 字节大端)、高度(4 字节)、位深(1 字节)、颜色类型(1 字节)。isPng 只做一件事:逐字节比对签名。不要用扩展名信文件——一个改了后缀的 .jpg 内容还是 JPEG,签名才会说真话。这也是资产数据库「内容哈希是判据」的延续:格式判断同样只看内容。

channelsOf 把颜色类型映射成通道数:0 灰度→1、2 真彩→3、6 真彩+alpha→4。formatFor 进一步归一成渲染友好的标签:灰度→luminance8、真彩→rgb8、真彩+alpha→rgba8。格式千变,信息归一——下游(纹理分配、压缩选择)只认 ImageInfo,不认文件后缀。

JPEG 的段扫描:跳过噪声找 SOF

JPEG 没有固定偏移的头,它是一串「段」:每个段 FF <marker> <长度> <载荷>。宽高藏在 SOF(Start of Frame,FF C0 那批)里。jpegInfo 从头扫描:读到 FF 就检查 marker 是不是 SOF 家族(0xC0–0xCF,排除 C4/C8/CC 这些非帧段),是则按段内偏移读出精度、高度、宽度、组件数,不是则按段长跳到下一段。段扫描是「跳过无关数据、直达目标」的范本——真实解码器就是这么扫过一堆 DQT/DHT 段才找到 SOF 的。

对标文件探测与纹理导入

Godot 的图片导入文档列出支持的格式和若干解码限制。helio 本节在导入前读取 PNG 和 JPEG 的尺寸等头部信息。该结果适合预览和初步筛选,完整解码与损坏检测由后续处理负责。 Godot 图片导入

可运行产物:6 条用例

下面 src/image-header.ts 层级 L1,完整可编译,命令 node --test test/04-1-image-header-decode.test.ts:

// file: src/image-header.ts
// tier: L1
// verify: node --test test/04-1-image-header-decode.test.ts
//
// 资产管线(第四章):图像导入——解码与格式归一。
// 不引入解码库,先做「头解析」:PNG 签名 + IHDR、JPEG SOI + SOF。
// 头解析给编辑器的价值远超文件格式本身:不加载全图就能拿到宽高与通道,
// 缩略图(第 11 章)和尺寸估算都靠它。归一:把不同格式收敛成统一的
// ImageInfo——「格式千变,信息归一」。

export interface ImageInfo {
  width: number;
  height: number;
  channels: number;
  /** 归一后的通道格式。 */
  format: 'rgba8' | 'rgb8' | 'luminance8' | 'unknown';
  /** 来源格式。 */
  source: 'png' | 'jpeg' | 'unknown';
}

/** PNG 8 字节签名:89 50 4E 47 0D 0A 1A 0A。 */
export function isPng(bytes: Uint8Array): boolean {
  if (bytes.length < 8) return false;
  const sig = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
  for (let i = 0; i < 8; i++) {
    if (bytes[i] !== sig[i]) return false;
  }
  return true;
}

/** JPEG 起始:FF D8 FF(SOI + 第一个 marker)。 */
export function isJpeg(bytes: Uint8Array): boolean {
  if (bytes.length < 4) return false;
  return bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff;
}

/** 解析 PNG IHDR:签名 8 字节 + length(4) + type(4) 之后是宽高。 */
function pngInfo(bytes: Uint8Array): ImageInfo | null {
  if (!isPng(bytes) || bytes.length < 26) return null;
  // 签名后的第一个 chunk 必须是 IHDR
  if (String.fromCharCode(bytes[12], bytes[13], bytes[14], bytes[15]) !== 'IHDR') return null;
  const width = readU32(bytes, 16);
  const height = readU32(bytes, 20);
  const colorType = bytes[25];
  const channels = channelsOf(colorType);
  if (channels === 0) return null;
  return { width, height, channels, format: formatFor(colorType), source: 'png' };
}

/** PNG 颜色类型 → 通道数;未知返回 0。 */
function channelsOf(colorType: number): number {
  switch (colorType) {
    case 0: return 1; // 灰度
    case 2: return 3; // 真彩
    case 3: return 1; // 索引(调色板)
    case 4: return 2; // 灰度 + alpha
    case 6: return 4; // 真彩 + alpha
    default: return 0;
  }
}

function formatFor(colorType: number): ImageInfo['format'] {
  switch (colorType) {
    case 0: return 'luminance8';
    case 2: return 'rgb8';
    case 6: return 'rgba8';
    default: return 'unknown';
  }
}

/** 解析 JPEG:扫描段找 SOF(FF C0),读精度/高/宽/组件。 */
function jpegInfo(bytes: Uint8Array): ImageInfo | null {
  if (!isJpeg(bytes)) return null;
  // 从 offset 2(跳过 SOI)开始扫 marker 段
  let i = 2;
  while (i + 9 < bytes.length) {
    if (bytes[i] !== 0xff) {
      i++;
      continue;
    }
    const marker = bytes[i + 1];
    if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
      // SOF:段长(2) 精度(1) 高(2) 宽(2) 组件(1),marker 在 i
      const height = readU16(bytes, i + 5);
      const width = readU16(bytes, i + 7);
      const components = bytes[i + 9];
      const channels = components === 1 ? 1 : components === 4 ? 4 : 3;
      return {
        width,
        height,
        channels,
        format: channels === 1 ? 'luminance8' : 'rgb8',
        source: 'jpeg',
      };
    }
    const segLen = readU16(bytes, i + 2);
    i += 2 + segLen;
  }
  return null;
}

function readU32(bytes: Uint8Array, offset: number): number {
  return (bytes[offset] << 24) | (bytes[offset + 1] << 16) | (bytes[offset + 2] << 8) | bytes[offset + 3];
}

function readU16(bytes: Uint8Array, offset: number): number {
  return (bytes[offset] << 8) | bytes[offset + 1];
}

/** 按签名路由解析;不认识的格式返回 null。 */
export function parseImageHeader(bytes: Uint8Array): ImageInfo | null {
  if (isPng(bytes)) return pngInfo(bytes);
  if (isJpeg(bytes)) return jpegInfo(bytes);
  return null;
}

两个健壮性细节。pngInfo 检查了「签名后第一个 chunk 必须是 IHDR」——签名对了但内容乱来的文件照样拒绝。jpegInfo 的段扫描带边界检查(i + 9 < bytes.length),绝不会越界读。解析器面对的是敌意数据,这是所有导入器的共识。

可运行产物:6 条用例

下面是 test/04-1-image-header-decode.test.ts 层级 L1,命令 node --test test/04-1-image-header-decode.test.ts:

// file: test/04-1-image-header-decode.test.ts
// tier: L1
// verify: node --test test/04-1-image-header-decode.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { isPng, isJpeg, parseImageHeader } from '../src/image-header.ts';

const PNG_SIG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];

/** 构造一段最小 PNG 头(签名 + IHDR)。 */
function pngHeader(width: number, height: number, colorType: number): Uint8Array {
  const b = new Uint8Array(26);
  b.set(PNG_SIG, 0);
  b[11] = 13; // IHDR chunk 长度
  b.set([0x49, 0x48, 0x44, 0x52], 12); // 'IHDR'
  b[16] = width >>> 24;
  b[17] = width >>> 16;
  b[18] = width >>> 8;
  b[19] = width;
  b[20] = height >>> 24;
  b[21] = height >>> 16;
  b[22] = height >>> 8;
  b[23] = height;
  b[24] = 8; // 位深
  b[25] = colorType;
  return b;
}

/** 构造一段最小 JPEG 头(SOI + SOF0)。 */
function jpegHeader(width: number, height: number, components: number): Uint8Array {
  const b = new Uint8Array(12);
  b[0] = 0xff;
  b[1] = 0xd8;
  b[2] = 0xff;
  b[3] = 0xc0; // SOF0
  b[5] = 11; // 段长
  b[6] = 8; // 精度
  b[7] = height >>> 8;
  b[8] = height;
  b[9] = width >>> 8;
  b[10] = width;
  b[11] = components;
  return b;
}

test('isPng/isJpeg 按签名识别格式', () => {
  assert.equal(isPng(pngHeader(64, 64, 6)), true);
  assert.equal(isJpeg(jpegHeader(64, 64, 3)), true);
  assert.equal(isPng(new Uint8Array([1, 2, 3])), false);
});

test('PNG IHDR 解析出宽高与通道(真彩+alpha → 4 通道)', () => {
  const info = parseImageHeader(pngHeader(256, 128, 6))!;
  assert.equal(info.width, 256);
  assert.equal(info.height, 128);
  assert.equal(info.channels, 4);
  assert.equal(info.format, 'rgba8');
  assert.equal(info.source, 'png');
});

test('PNG 颜色类型归一:灰度→luminance8、真彩→rgb8', () => {
  const gray = parseImageHeader(pngHeader(32, 32, 0))!;
  assert.equal(gray.channels, 1);
  assert.equal(gray.format, 'luminance8');
  const rgb = parseImageHeader(pngHeader(32, 32, 2))!;
  assert.equal(rgb.channels, 3);
  assert.equal(rgb.format, 'rgb8');
});

test('JPEG SOF0 解析出宽高与组件数', () => {
  const info = parseImageHeader(jpegHeader(640, 480, 3))!;
  assert.equal(info.width, 640);
  assert.equal(info.height, 480);
  assert.equal(info.channels, 3);
  assert.equal(info.source, 'jpeg');
});

test('太短或非法数据 → null(不崩溃)', () => {
  assert.equal(parseImageHeader(new Uint8Array(0)), null);
  assert.equal(parseImageHeader(new Uint8Array([0x89, 0x50])), null); // 只有签名开头
  assert.equal(parseImageHeader(new TextEncoder().encode('plain text')), null);
});

test('PNG 签名后不是 IHDR → 解析失败返回 null', () => {
  const b = pngHeader(64, 64, 6);
  b.set([0x00, 0x00, 0x00, 0x00], 12); // 伪造非 IHDR type
  assert.equal(parseImageHeader(b), null);
});

本机实测(Node v26.5.0,node --test test/04-1-image-header-decode.test.ts):tests 6、pass 6、fail 0,耗时约 40 ms。

测试里的 pngHeader/jpegHeader 是手工构造的最小字节流——测试不依赖任何图片文件,纯字节验证解析器。第五条与第六条是健壮性双保险:太短、纯文本、只有签名、伪造 type,全部返回 null 而不是抛异常。

小结

  • 头解析让你不加载全图就知道宽高通道——缩略图、尺寸估算的地基。
  • PNG:8 字节签名 + IHDR 里的宽高与颜色类型;JPEG:段扫描找 SOF。
  • 归一:rgba8/rgb8/luminance8 统一标签,下游只认 ImageInfo。
  • 别信扩展名,信签名;解析器面对的是敌意数据,必须返回 null 而非崩溃。
  • 下一节决定「导入成什么样」:纹理参数与压缩设置——寻址、过滤、mip、sRGB、2 的幂尺寸。

阅读导航:上一节:3.3 可扩展导入器:插件与接管 · 下一节:4.2 纹理参数与压缩设置 。

继续阅读

探索更多技术文章

浏览归档,发现更多关于系统设计、工具链和工程实践的内容。

全部文章 返回首页

「books」更多文章

  1. 《大规模分布式计算深入解析·向量数据库与 AI 检索内核》 · 目录与学习路径(45 篇)
  2. 《大规模分布式计算深入解析》15.3 自研向量引擎:可执行骨架与工程缺口
  3. 《大规模分布式计算深入解析》14.1 Milvus:组件架构、段管理与检索链路