动图只剩第一帧或变成纵向长图
动图只剩第一帧、变成纵向长图或缩放后帧错位,需要分别检查加载页数、帧高与时间元数据。下面用能直接辨认帧序的三帧 GIF 展示这些情况。
先观察实际输出
Section titled “先观察实际输出”输入的三帧依次为红、绿、蓝背景,分别带一、二、三根白条及移动标记。每帧为 320×180,延迟依次为 200 / 400 / 600 ms,无限循环。动画默认显示实际导出的首帧,点击按钮播放或停止;即使不播放,也能通过长图和元数据检查帧结构。
govips v2.20.0 / libvips 8.17.3

{"Bitdepth":8,"Dither":0,"Effort":7,"NumPages":-1,"pageHeight":180,"resize":false}帧数:3 · 200 / 400 / 600 ms · 循环:无限下载实际输出
{"Bitdepth":8,"Dither":0,"Effort":7,"NumPages":1,"pageHeight":180,"resize":false}下载实际输出
{"Bitdepth":8,"Dither":0,"Effort":7,"NumPages":-1,"pageHeight":180,"resize":false}帧数:3 · 200 / 400 / 600 ms · 循环:无限下载实际输出
{"Bitdepth":8,"Dither":0,"Effort":7,"NumPages":-1,"pageHeight":540,"resize":false}下载实际输出
{"Bitdepth":8,"Dither":0,"Effort":7,"NumPages":-1,"pageHeight":90,"resize":true}帧数:3 · 200 / 400 / 600 ms · 循环:无限下载实际输出sharp 0.35.5 / libvips 8.18.7

{"animated":true,"colours":256,"dither":0,"effort":7,"delay":[200,400,600],"loop":0}帧数:3 · 200 / 400 / 600 ms · 循环:无限下载实际输出
{"animated":false}下载实际输出
{"animated":true,"colours":256,"dither":0,"effort":7,"delay":[200,400,600],"loop":0}帧数:3 · 200 / 400 / 600 ms · 循环:无限下载实际输出
{"raw":true,"pageHeight":"omitted"}下载实际输出
{"animated":true,"width":160,"pageHeight":90,"colours":256,"dither":0,"effort":7,"delay":[200,400,600],"loop":0}帧数:3 · 200 / 400 / 600 ms · 循环:无限下载实际输出pyvips 3.2.0 / libvips 8.17.3

{"n":-1,"bitdepth":8,"dither":0,"effort":7}帧数:3 · 200 / 400 / 600 ms · 循环:无限下载实际输出
{"n":1,"bitdepth":8,"dither":0,"effort":7}下载实际输出
{"n":-1,"bitdepth":8,"dither":0,"effort":7}帧数:3 · 200 / 400 / 600 ms · 循环:无限下载实际输出
{"page-height":"omitted","bitdepth":8,"dither":0,"effort":7}下载实际输出
{"n":-1,"scale":0.5,"page-height":90,"bitdepth":8,"dither":0,"effort":7}帧数:3 · 200 / 400 / 600 ms · 循环:无限下载实际输出vipsCli 8.17.3 / libvips 8.17.3

{"n":-1,"page-height":180}帧数:3 · 200 / 400 / 600 ms · 循环:无限下载实际输出
{"n":1,"page-height":180}下载实际输出
{"n":-1,"page-height":180}帧数:3 · 200 / 400 / 600 ms · 循环:无限下载实际输出
{"n":-1,"page-height":"omitted"}下载实际输出
{"n":-1,"page-height":90}帧数:3 · 200 / 400 / 600 ms · 循环:无限下载实际输出分清三个问题
Section titled “分清三个问题”| 观察到的现象 | 本例改变了什么 | 修复方式 |
|---|---|---|
| 只看到红色第一帧 | 只加载一页 | govips 显式设置 NumPages=-1;pyvips/CLI 设置 n=-1;sharp 设置 animated: true |
| 三帧排成 320×540 的长图 | 将所有解码像素作为原始图重建,遗漏每帧高度 | 重新建立动画时设置正确的 page-height,并设置 delay 与 loop;sharp 原始输入使用 raw.pageHeight |
| 缩放后帧界线不正确 | 帧高没有与单帧几何同步 | 本例缩放后应为每帧 160×90,共三帧;CLI 显式使用保存参数 page-height=90,pyvips 显式更新图像字段 |
libvips 的多页(multi-page)模型把帧按纵向堆叠。原动图加载全部帧后,总解码高度是 540,page-height 是 180;它们不是两个可互换的尺寸。仅复制原始像素不会保留页数、帧高与时间信息。
正确加载、变换与导出
Section titled “正确加载、变换与导出”govips v2.20.0 的本例在全帧加载后缩放,并保留每帧边界。sharp 对动画执行自身的分页缩放。pyvips 与 CLI 显式校正缩放后的帧高;不要把某个 binding 的便捷封装当作所有入口的默认行为。
完整程序同时生成故障对照与正确输出。重建原始像素的长图是受控失败案例,不是要求读者在正常转换中先解码成整幅长图。
运行命令
go run . three-frames.gif output/完整源码
package main
import (
"fmt"
"os"
"path/filepath"
"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", "first-frame", "all-frames", "tall-strip", "resized"} {
output, err := makeVariant(args[1], args[2], id)
if err != nil {
return err
}
outputs = append(outputs, output)
}
return recipeutil.WriteResult(args[2], "animation-pages", args[1], outputs)
}
func makeVariant(input, dir, id string) (recipeutil.Output, error) {
params := vips.NewImportParams()
if id != "first-frame" {
params.NumPages.Set(-1)
}
image, err := vips.LoadImageFromFile(input, params)
if err != nil {
return recipeutil.Output{}, err
}
defer func() { image.Close() }()
if id == "tall-strip" {
pixels, err := image.ToBytes()
if err != nil {
return recipeutil.Output{}, err
}
tall, err := vips.NewImageFromMemory(pixels, image.Width(), image.Height(), image.Bands(), vips.BandFormatUchar, vips.InterpretationSRGB)
if err != nil {
return recipeutil.Output{}, err
}
image.Close()
image = tall
// No SetPageHeight: the new raw image is a single tall page.
}
if id == "resized" {
if err := image.Resize(0.5, vips.KernelNearest); err != nil {
return recipeutil.Output{}, err
}
}
if id == "all-frames" || id == "resized" || id == "source" {
if err := image.SetPageDelay([]int{200, 400, 600}); err != nil {
return recipeutil.Output{}, err
}
if err := image.SetLoop(0); err != nil {
return recipeutil.Output{}, err
}
}
export := vips.NewGifExportParams()
export.Dither = 0
export.Bitdepth = 8
export.Effort = 7
data, meta, err := image.ExportGIF(export)
if err != nil {
return recipeutil.Output{}, err
}
name := id + ".gif"
if err := os.WriteFile(filepath.Join(dir, name), data, 0o644); err != nil {
return recipeutil.Output{}, err
}
n := 1
if id != "first-frame" {
n = -1
}
return recipeutil.Output{Path: name, Format: "gif", Width: meta.Width, Height: meta.Height, Size: len(data), Parameters: map[string]any{"NumPages": n, "resize": id == "resized", "pageHeight": image.PageHeight(), "Dither": 0, "Bitdepth": 8, "Effort": 7}}, nil
}运行命令
node index.mjs three-frames.gif output/完整源码
import sharp from 'sharp';
import { mkdir, 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 options = { colours: 256, dither: 0, effort: 7, delay: [200, 400, 600], loop: 0 };
await save(sharp(input, { animated: true }).gif(options), 'source.gif', { animated: true, ...options });
await save(sharp(input).gif({ colours: 256, dither: 0, effort: 7 }), 'first-frame.gif', { animated: false });
await save(sharp(input, { animated: true }).gif(options), 'all-frames.gif', { animated: true, ...options });
await save(sharp(input, { animated: true }).resize(160, 90, { kernel: 'nearest' }).gif(options), 'resized.gif', { animated: true, width: 160, pageHeight: 90, ...options });
const { data, info } = await sharp(input, { animated: true }).raw().toBuffer({ resolveWithObject: true });
// Deliberately omit raw.pageHeight: 540 rows now represent one tall frame.
await save(sharp(data, { raw: { width: info.width, height: info.height, channels: info.channels } }).gif({ colours: 256, dither: 0, effort: 7 }), 'tall-strip.gif', { raw: true, pageHeight: 'omitted' });
await writeFile(path.join(out, 'result.json'), JSON.stringify({ recipeId: 'animation-pages', input: path.basename(input), generator: { sharp: sharp.versions.sharp, libvips: sharp.versions.vips }, outputs }, null, 2) + '\n');运行命令
python3 main.py three-frames.gif 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})
options = dict(bitdepth=8, dither=0, effort=7)
image = pyvips.Image.new_from_file(str(source), n=-1)
image.gifsave(str(out / "source.gif"), **options)
record("source.gif", {"n": -1, **options})
pyvips.Image.new_from_file(str(source)).gifsave(str(out / "first-frame.gif"), **options)
record("first-frame.gif", {"n": 1, **options})
image.gifsave(str(out / "all-frames.gif"), **options)
record("all-frames.gif", {"n": -1, **options})
small = image.resize(0.5, kernel="nearest")
small.set_type(pyvips.GValue.gint_type, "page-height", 90)
small.gifsave(str(out / "resized.gif"), **options)
record("resized.gif", {"n": -1, "scale": 0.5, "page-height": 90, **options})
tall = pyvips.Image.new_from_memory(image.write_to_memory(), image.width, image.height, image.bands, "uchar").copy(interpretation="srgb")
# No page-height metadata is attached to this reconstructed raw image.
tall.gifsave(str(out / "tall-strip.gif"), **options)
record("tall-strip.gif", {"page-height": "omitted", **options})
(out / "result.json").write_text(json.dumps({"recipeId": "animation-pages", "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 three-frames.gif 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 gifsave "$input[n=-1]" "$out/source.gif" --bitdepth 8 --dither 0 --effort 7
vips gifsave "$input" "$out/first-frame.gif" --bitdepth 8 --dither 0 --effort 7
vips gifsave "$input[n=-1]" "$out/all-frames.gif" --bitdepth 8 --dither 0 --effort 7
vips resize "$input[n=-1]" "$scratch/resized.v" 0.5 --kernel nearest
vips gifsave "$scratch/resized.v" "$out/resized.gif" --page-height 90 --bitdepth 8 --dither 0 --effort 7
# Raw pixels carry no frame height, delay, or loop metadata.
vips rawsave "$input[n=-1]" "$scratch/strip.raw"
vips rawload "$scratch/strip.raw" "$scratch/strip.v" 320 540 4
vips copy "$scratch/strip.v" "$scratch/rgb.v" --interpretation srgb
vips gifsave "$scratch/rgb.v" "$out/tall-strip.gif" --bitdepth 8 --dither 0 --effort 7
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.gif', 'parameters': {'n': -1, 'page-height': 180}}, {'path': 'first-frame.gif', 'parameters': {'n': 1, 'page-height': 180}}, {'path': 'all-frames.gif', 'parameters': {'n': -1, 'page-height': 180}}, {'path': 'tall-strip.gif', 'parameters': {'n': -1, 'page-height': 'omitted'}}, {'path': 'resized.gif', 'parameters': {'n': -1, 'page-height': 90}}]
(out / "result.json").write_text(json.dumps({"recipeId": "animation-pages", "input": source.name, "generator": {"vipsCli": version, "libvips": version}, "outputs": outputs}, indent=2) + "\n")
METADATA检查帧序与播放时间
Section titled “检查帧序与播放时间”- 重新加载导出的全部帧,检查页数为三、总高等于帧高乘以三。
- 逐帧检查红、绿、蓝背景与白条数量,避免只看总尺寸就漏掉帧序颠倒。
- 检查延迟数组仍为 200 / 400 / 600 ms,loop 为 0;本例的 0 表示无限循环。
- 对只取第一帧与长图案例确认页数为一,避免查看器的显示方式掩盖编码结果。
本例逐入口检查了原尺寸的完整帧像素、缩放后的帧序与几何、延迟和循环,不据此宣称所有动画操作都等价。
验证边界与来源
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。
本例仅验证 GIF、三张不同帧与精确 0.5 倍缩放。它不重新复现旧版本的帧错位缺陷,也不覆盖 AVIF、PDF、多页 TIFF、重复帧合并、非整数舍入或所有旋转操作。Similarity、SmartCrop 和 Gravity 仍不能从本例推导多页支持。