转换后偏色、ICC 丢失或 CMYK 失真
色偏不一定发生在编码阶段。先区分“改变像素以转换颜色”和“删除描述像素含义的 ICC 配置文件(ICC profile)”。下面使用受控的线性 RGB 样本,直接展示两者的区别。
先观察实际输出
Section titled “先观察实际输出”样本由色块和灰度渐变组成,使用与 sRGB 相同的原色和 D65 白点,但传递曲线为线性 gamma 1.0;因此它不是普通 sRGB,也不是 P3 或 CMYK 样本。嵌入的 ICC 描述这个差异。
在支持 ICC 的浏览器中,带配置文件的源图和正确转换到 sRGB 的输出应接近;直接删 ICC 的输出通常更暗。浏览器、显示器和色彩管理设置会影响观感,下面的 RGB 采样与 ICC 检查用于确认实际行为。
govips v2.20.0 / libvips 8.17.3

{"operation":"source","target":"unchanged"}ICC: 568 字节下载实际输出
{"operation":"stripped","target":"unchanged"}ICC: 无下载实际输出
{"operation":"converted","target":"sRGB"}ICC: 480 字节下载实际输出| x | 参考输入 | 未转换就删除 ICC | 先转换到 sRGB |
|---|---|---|---|
| 64 | 64, 64, 64 | 64, 64, 64 | 137, 137, 137 |
| 192 | 128, 32, 16 | 128, 32, 16 | 188, 99, 71 |
| 320 | 16, 128, 32 | 16, 128, 32 | 71, 188, 99 |
| 448 | 32, 16, 128 | 32, 16, 128 | 99, 71, 188 |
| 576 | 128, 128, 128 | 128, 128, 128 | 188, 188, 188 |
sharp 0.35.5 / libvips 8.18.7

{"operation":"keepIccProfile"}ICC: 568 字节下载实际输出
{"operation":"remove iCCP before decode; no input ICC conversion"}ICC: 无下载实际输出
{"operation":"withIccProfile","target":"sRGB"}ICC: 480 字节下载实际输出| x | 参考输入 | 未转换就删除 ICC | 先转换到 sRGB |
|---|---|---|---|
| 64 | 64, 64, 64 | 64, 64, 64 | 137, 137, 137 |
| 192 | 128, 32, 16 | 128, 32, 16 | 188, 99, 71 |
| 320 | 16, 128, 32 | 16, 128, 32 | 71, 188, 99 |
| 448 | 32, 16, 128 | 32, 16, 128 | 99, 71, 188 |
| 576 | 128, 128, 128 | 128, 128, 128 | 188, 188, 188 |
pyvips 3.2.0 / libvips 8.17.3

{"operation":"retain embedded ICC"}ICC: 568 字节下载实际输出
{"operation":"remove ICC without conversion"}ICC: 无下载实际输出
{"operation":"icc_transform","embedded":true,"target":"sRGB","intent":"perceptual"}ICC: 480 字节下载实际输出| x | 参考输入 | 未转换就删除 ICC | 先转换到 sRGB |
|---|---|---|---|
| 64 | 64, 64, 64 | 64, 64, 64 | 137, 137, 137 |
| 192 | 128, 32, 16 | 128, 32, 16 | 188, 99, 71 |
| 320 | 16, 128, 32 | 16, 128, 32 | 71, 188, 99 |
| 448 | 32, 16, 128 | 32, 16, 128 | 99, 71, 188 |
| 576 | 128, 128, 128 | 128, 128, 128 | 188, 188, 188 |
vipsCli 8.17.3 / libvips 8.17.3

{"operation":"copy; retain ICC"}ICC: 568 字节下载实际输出
{"operation":"keep=none; no ICC transform"}ICC: 无下载实际输出
{"operation":"icc_transform srgb; embedded; perceptual"}ICC: 480 字节下载实际输出| x | 参考输入 | 未转换就删除 ICC | 先转换到 sRGB |
|---|---|---|---|
| 64 | 64, 64, 64 | 64, 64, 64 | 137, 137, 137 |
| 192 | 128, 32, 16 | 128, 32, 16 | 188, 99, 71 |
| 320 | 16, 128, 32 | 16, 128, 32 | 71, 188, 99 |
| 448 | 32, 16, 128 | 32, 16, 128 | 99, 71, 188 |
| 576 | 128, 128, 128 | 128, 128, 128 | 188, 188, 188 |
读取三条处理路径
Section titled “读取三条处理路径”| 路径 | 像素与配置文件发生了什么 | 如何验证 |
|---|---|---|
| 保留源图 | 保留线性 RGB 的配置文件及像素;sharp 的保留路径允许一个 8-bit 等级的往返舍入 | 检查 ICC 存在,并比较完整图像像素 |
| 直接删除 ICC | 不转换像素,只删除配置文件;查看器通常按 sRGB 解释这些值 | 检查 ICC 缺失,同时像素与输入完全相同 |
| 转换到 sRGB | 按源 ICC 重新计算目标像素,并嵌入目标 ICC | 检查像素变化与目标 ICC;线性灰度 64 约变为 sRGB 137,128 约变为 188 |
sharp 通常自动执行输入 ICC 转换。因此本例的错误路径会在解码前明确移除 PNG 的 ICC 数据块,而不是声称普通 sharp(...).png() 一定导致这种偏色。其他入口也各自明确表达“只删除”或“先转换”。
正确转换与元数据策略
Section titled “正确转换与元数据策略”本例目标为 sRGB,使用源图的嵌入 ICC 做变换。不要把“有 ICC”当作“已转换”,也不要把 colourspace 的色彩解释转换自动等同于基于源配置文件的 ICC 变换。
govips v2.20.0 的 WebP 默认路径会保留源 ICC;Keep 未设置时由 StripMetadata 决定,显式 ForeignKeepIcc 或 ForeignKeepNone 优先。保存选项影响元数据保留,不能代替像素的色彩转换。本例用 PNG 隔离配置文件与像素关系,不把它当作所有格式的元数据默认值证明。
运行命令
go run . linear-rgb.png output/完整源码
package main
import (
"fmt"
"os"
"github.com/davidbyttow/govips/v2/vips"
"github.com/webp-sh/vips-handbook/examples/internal/recipeutil"
)
func main() {
if err := run(os.Args); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run(args []string) error {
if len(args) != 3 {
return fmt.Errorf("usage: main INPUT OUTPUT_DIRECTORY")
}
if err := os.MkdirAll(args[2], 0o755); err != nil {
return err
}
if err := vips.Startup(nil); err != nil {
return err
}
defer vips.Shutdown()
outputs := []recipeutil.Output{}
for _, id := range []string{"source", "stripped", "converted"} {
output, err := makeVariant(args[1], args[2], id)
if err != nil {
return err
}
outputs = append(outputs, output)
}
return recipeutil.WriteResult(args[2], "colour-profile", args[1], outputs)
}
func makeVariant(input, dir, id string) (recipeutil.Output, error) {
image, err := vips.NewImageFromFile(input)
if err != nil {
return recipeutil.Output{}, err
}
defer image.Close()
if id == "stripped" {
if err := image.RemoveICCProfile(); err != nil {
return recipeutil.Output{}, err
}
}
if id == "converted" {
if err := image.TransformICCProfile("srgb"); err != nil {
return recipeutil.Output{}, err
}
}
return recipeutil.ExportPng(image, dir, id+".png", map[string]any{"operation": id, "target": map[bool]string{true: "sRGB", false: "unchanged"}[id == "converted"]})
}运行命令
node index.mjs linear-rgb.png output/完整源码
import sharp from 'sharp';
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import path from 'node:path';
const [input, out] = process.argv.slice(2);
if (!input || !out) throw new Error('usage: node index.mjs INPUT OUTPUT_DIRECTORY');
await mkdir(out, { recursive: true });
const outputs = [];
async function save(pipeline, name, parameters) {
await pipeline.toFile(path.join(out, name));
outputs.push({ path: name, parameters });
}
const buffer = await readFile(input);
// sharp normally performs input ICC conversion. For this deliberate failure,
// remove only the PNG iCCP chunk before decoding; other chunks and CRCs stay intact.
function withoutICC(png) {
if (png.subarray(0, 8).toString('hex') !== '89504e470d0a1a0a') throw new Error('expected PNG');
const chunks = [png.subarray(0, 8)];
for (let offset = 8; offset < png.length;) {
if (offset + 12 > png.length) throw new Error('truncated PNG chunk');
const end = offset + 12 + png.readUInt32BE(offset);
if (end > png.length) throw new Error('truncated PNG payload');
if (png.toString('ascii', offset + 4, offset + 8) !== 'iCCP') chunks.push(png.subarray(offset, end));
offset = end;
}
return Buffer.concat(chunks);
}
await save(sharp(buffer).keepIccProfile().png(), 'source.png', { operation: 'keepIccProfile' });
await save(sharp(withoutICC(buffer)).png(), 'stripped.png', { operation: 'remove iCCP before decode; no input ICC conversion' });
await save(sharp(buffer).withIccProfile('srgb').png(), 'converted.png', { operation: 'withIccProfile', target: 'sRGB' });
await writeFile(path.join(out, 'result.json'), JSON.stringify({ recipeId: 'colour-profile', input: path.basename(input), generator: { sharp: sharp.versions.sharp, libvips: sharp.versions.vips }, outputs }, null, 2) + '\n');运行命令
python3 main.py linear-rgb.png output/完整源码
import json
from pathlib import Path
import sys
import pyvips
if len(sys.argv) != 3:
raise SystemExit("usage: python3 main.py INPUT OUTPUT_DIRECTORY")
source, out = Path(sys.argv[1]), Path(sys.argv[2])
out.mkdir(parents=True, exist_ok=True)
outputs = []
def record(name, parameters):
outputs.append({"path": name, "parameters": parameters})
image = pyvips.Image.new_from_file(str(source))
image.pngsave(str(out / "source.png"))
record("source.png", {"operation": "retain embedded ICC"})
wrong = image.copy()
wrong.remove("icc-profile-data")
wrong.pngsave(str(out / "stripped.png"))
record("stripped.png", {"operation": "remove ICC without conversion"})
image.icc_transform("srgb", embedded=True, intent="perceptual").pngsave(str(out / "converted.png"))
record("converted.png", {"operation": "icc_transform", "embedded": True, "target": "sRGB", "intent": "perceptual"})
(out / "result.json").write_text(json.dumps({"recipeId": "colour-profile", "input": source.name, "generator": {"pyvips": pyvips.__version__, "libvips": ".".join(str(pyvips.version(i)) for i in range(3))}, "outputs": outputs}, indent=2) + "\n")运行命令
bash run.sh linear-rgb.png output/完整源码
#!/usr/bin/env bash
set -euo pipefail
if [[ $# -ne 2 ]]; then
echo 'usage: bash run.sh INPUT OUTPUT_DIRECTORY' >&2
exit 2
fi
input="$1"
out="$2"
mkdir -p "$out"
scratch="$(mktemp -d)"
trap 'rm -rf "$scratch"' EXIT
vips copy "$input" "$out/source.png"
vips copy "$input" "$out/stripped.png[keep=none]"
vips icc_transform "$input" "$out/converted.png" srgb --embedded --intent perceptual
python3 - "$input" "$out" <<'METADATA'
import json
from pathlib import Path
import subprocess
import sys
source, out = Path(sys.argv[1]), Path(sys.argv[2])
version = subprocess.check_output(["vips", "--version"], text=True).strip().removeprefix("vips-")
outputs = [{'path': 'source.png', 'parameters': {'operation': 'copy; retain ICC'}}, {'path': 'stripped.png', 'parameters': {'operation': 'keep=none; no ICC transform'}}, {'path': 'converted.png', 'parameters': {'operation': 'icc_transform srgb; embedded; perceptual'}}]
(out / "result.json").write_text(json.dumps({"recipeId": "colour-profile", "input": source.name, "generator": {"vipsCli": version, "libvips": version}, "outputs": outputs}, indent=2) + "\n")
METADATA判断修复是否有效
Section titled “判断修复是否有效”- 确认输入确实带有预期 ICC,记录工作空间和输出目标。
- 在加载、变换和导出后分别检查 ICC 与像素,定位配置文件被移除或错误解释的位置。
- 同时检查目标配置文件与灰度采样,避免把复制一个 ICC 数据块误认为完成转换。
- 如需删除元数据,先完成明确的目标转换,再决定是否保留目标 ICC,并在真实查看环境复核。
CMYK 的结果依赖源配置文件、目标配置文件和渲染意图。不能把问题概括为“只要先 resize 就一定偏色”;处理顺序需要结合工作空间与实际算子验证,本例不提供 CMYK 转换结论。
验证边界与来源
Section titled “验证边界与来源”复核日期:2026-10-26。参考环境为 govips v2.20.0 / libvips 8.17.3;sharp 0.35.5 使用 libvips 8.18.7,pyvips 3.2.0 与 CLI 使用 libvips 8.17.3。
本例验证程序生成的三通道线性 RGB、ICC 删除和 sRGB 转换,不覆盖 CMYK、P3、HDR、所有 EXIF/IPTC 清理规则,也不保证跨入口逐像素相同。更多概念见色彩管理与 ICC。