15 分钟 Quickstart
本节将经典的“读取 → 处理 → 导出”流程落地为一个可对照的任务:把 input.jpg 缩小到不超过 640 × 640,不放大小图,输出质量为 82 的 output.webp。govips、sharp、pyvips 和 vips CLI 是四种常用入口;Image 是 Elixir 上的额外比较入口。
1. 准备输入
Section titled “1. 准备输入”运行示例时,可以将自己的 JPEG 命名为 input.jpg;尺寸和画面不同会产生不同的输出数据。


参考输出由 govips v2.20.0 / libvips 8.17.3 在锁定的 Docker Runner 中实际生成。
2. 选择入口并运行
Section titled “2. 选择入口并运行”运行命令
go run . input.jpg 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: quickstart-thumbnail <input.jpg> <output-directory>")
}
inputPath, outputDir := args[1], args[2]
if err := os.MkdirAll(outputDir, 0o755); err != nil {
return err
}
if err := vips.Startup(nil); err != nil {
return fmt.Errorf("start libvips: %w", err)
}
defer vips.Shutdown()
image, err := vips.NewThumbnailFromFile(inputPath, 640, 640, vips.InterestingNone)
if err != nil {
return fmt.Errorf("create thumbnail: %w", err)
}
defer image.Close()
output, err := recipeutil.ExportWebp(image, outputDir, "output.webp", 82, map[string]any{
"width": 640, "height": 640, "crop": "none", "withoutEnlargement": true,
})
if err != nil {
return err
}
if output.Width > 640 || output.Height > 640 {
return fmt.Errorf("unexpected thumbnail dimensions: %dx%d", output.Width, output.Height)
}
if err := recipeutil.WriteResult(outputDir, "quickstart-thumbnail", inputPath, []recipeutil.Output{output}); err != nil {
return err
}
fmt.Printf("quickstart-thumbnail: %dx%d, %d bytes\n", output.Width, output.Height, output.Size)
return nil
}运行命令
node index.mjs input.jpg output/完整源码
import { mkdir, writeFile } from 'node:fs/promises';
import path from 'node:path';
import sharp from 'sharp';
const [inputPath, outputDir] = process.argv.slice(2);
if (!inputPath || !outputDir) {
console.error('Usage: node index.mjs <input.jpg> <output-directory>');
process.exit(2);
}
try {
await mkdir(outputDir, { recursive: true });
const outputPath = path.join(outputDir, 'output.webp');
const writeResult = await sharp(inputPath)
.resize(640, 640, { fit: 'inside', withoutEnlargement: true })
.webp({ quality: 82 })
.toFile(outputPath);
if (writeResult.width > 640 || writeResult.height > 640) {
throw new Error(`Unexpected thumbnail dimensions: ${writeResult.width}x${writeResult.height}`);
}
await writeFile(
path.join(outputDir, 'result.json'),
`${JSON.stringify({
recipeId: 'quickstart-thumbnail',
generator: { sharp: sharp.versions.sharp, libvips: sharp.versions.vips },
input: path.basename(inputPath),
outputs: [{
path: 'output.webp',
format: writeResult.format,
width: writeResult.width,
height: writeResult.height,
size: writeResult.size,
}],
}, null, 2)}\n`,
);
console.log(`quickstart-thumbnail: ${writeResult.width}x${writeResult.height}, ${writeResult.size} bytes`);
} catch (error) {
console.error(error);
process.exit(1);
}运行命令
python3 main.py input.jpg output/完整源码
import sys
import json
import os
import pyvips
input_path, output_dir = sys.argv[1], sys.argv[2]
if not input_path or not output_dir:
print("Usage: python3 main.py <input.jpg> <output-directory>", file=sys.stderr)
raise SystemExit(2)
os.makedirs(output_dir, exist_ok=True)
output_path = os.path.join(output_dir, "output.webp")
try:
image = pyvips.Image.thumbnail(input_path, 640, height=640, size="down")
image.write_to_file(output_path, Q=82)
if image.width > 640 or image.height > 640:
raise ValueError(f"Unexpected thumbnail dimensions: {image.width}x{image.height}")
result_path = os.path.join(output_dir, "result.json")
with open(result_path, "w") as f:
json.dump({
"recipeId": "quickstart-thumbnail",
"generator": {
"pyvips": pyvips.__version__,
"libvips": f"{pyvips.version(0)}.{pyvips.version(1)}.{pyvips.version(2)}",
},
"input": os.path.basename(input_path),
"outputs": [{
"path": "output.webp",
"format": "webp",
"width": image.width,
"height": image.height,
"bands": image.bands,
"hasAlpha": image.hasalpha(),
"size": os.path.getsize(output_path),
}],
}, f, indent=2)
f.write("\n")
print(f"quickstart-thumbnail: {image.width}x{image.height}, {os.path.getsize(output_path)} bytes")
except pyvips.Error as error:
print(error, file=sys.stderr)
raise SystemExit(1)运行命令
bash run.sh input.jpg output/完整源码
#!/usr/bin/env bash
set -euo pipefail
INPUT="$1"
OUTPUT_DIR="$2"
if [ $# -ne 2 ]; then
echo "Usage: bash run.sh <input.jpg> <output-directory>" >&2
exit 2
fi
mkdir -p "$OUTPUT_DIR"
OUTPUT_WEBP="$OUTPUT_DIR/output.webp"
vips thumbnail "$INPUT" "$OUTPUT_WEBP[Q=82]" 640 --height 640 --size down
IDATA="$(vipsheader --all "$OUTPUT_WEBP")"
WIDTH="$(echo "$IDATA" | grep '^width:' | awk '{print $2}')"
HEIGHT="$(echo "$IDATA" | grep '^height:' | awk '{print $2}')"
BANDS="$(echo "$IDATA" | grep '^bands:' | awk '{print $2}')"
FILESIZE="$(stat -c%s "$OUTPUT_WEBP")"
LIBVIPS_VER="$(vips --version | sed 's/vips-//')"
if [ "$WIDTH" -gt 640 ] || [ "$HEIGHT" -gt 640 ]; then
echo "Unexpected thumbnail dimensions: ${WIDTH}x${HEIGHT}" >&2
exit 1
fi
cat > "$OUTPUT_DIR/result.json" << EOF
{
"recipeId": "quickstart-thumbnail",
"generator": {
"vipsCli": "${LIBVIPS_VER}",
"libvips": "${LIBVIPS_VER}"
},
"input": "$(basename "$INPUT")",
"outputs": [{
"path": "output.webp",
"format": "webp",
"width": ${WIDTH},
"height": ${HEIGHT},
"bands": ${BANDS},
"hasAlpha": false,
"size": ${FILESIZE}
}]
}
EOF
echo "quickstart-thumbnail: ${WIDTH}x${HEIGHT}, ${FILESIZE} bytes"运行命令
mix run main.exs input.jpg output/完整源码
defmodule QuickstartThumbnail do
def main([input_path, output_dir]) do
with :ok <- File.mkdir_p(output_dir),
{:ok, _} <- Application.ensure_all_started(:image),
{:ok, image} <-
Image.thumbnail(input_path, "640x640", fit: :contain, resize: :down, autorotate: false),
{width, height, bands} <- Image.shape(image),
:ok <- bounds(width, height),
output_path = Path.join(output_dir, "output.webp"),
{:ok, written} <- Image.write(image, output_path, quality: 82),
{:ok, stat} <- File.stat(output_path) do
output = %{
"path" => "output.webp",
"format" => "webp",
"width" => width,
"height" => height,
"bands" => bands,
"hasAlpha" => Image.has_alpha?(image),
"size" => stat.size
}
Handbook.Output.release(written)
Handbook.Output.release(image)
Handbook.Output.write_result!(output_dir, "quickstart-thumbnail", input_path, [output])
IO.puts("quickstart-thumbnail: #{width}x#{height}, #{stat.size} bytes")
else
{:error, reason} -> Handbook.Output.fail(reason)
end
end
defp bounds(width, height) when width <= 640 and height <= 640, do: :ok
defp bounds(width, height), do: {:error, "unexpected thumbnail dimensions: #{width}x#{height}"}
end
case System.argv() do
[_, _] = args -> QuickstartThumbnail.main(args)
_ -> Handbook.Output.fail("usage: mix run main.exs <input.jpg> <output-directory>")
end3. 检查结果
Section titled “3. 检查结果”至少确认 output.webp 存在且能被重新读取;宽和高都不超过 640;输入小于目标尺寸时没有被放大;输出格式确实是 WebP 而不是只改了扩展名。
- 格式: WEBP
- 尺寸: 640 × 427
- 通道数: 3
- 透明通道: 无
- 文件大小: 39,228 字节
- 生成环境: govips v2.20.0 / libvips 8.17.3
这几段代码表达同一个产品目标,但不是逐行等价:govips、pyvips 和 Image 直接调用 thumbnail 能力,sharp 用 resize({ fit: 'inside' }) 表达边界,CLI 则通过操作参数传递保存选项。
结果差在哪里
Section titled “结果差在哪里”同一张 1938 × 1292 的 JPEG,目标都是放进 640 像素且不放大,WebP quality 82。前四行是 2026-10-12 的执行结果;Image 一行是 2026-10-16 链接 libvips 8.17.3 的执行结果。
| 入口 | libvips | 输出尺寸 | 字节数 |
|---|---|---|---|
| govips v2.20.0 | 8.17.3 | 640 × 427 | 39,228 |
| sharp 0.35.5 | 8.18.7 | 640 × 427 | 35,924 |
| pyvips 3.2.0 | 8.17.3 | 640 × 427 | 39,228 |
| vips CLI 8.17.3 | 8.17.3 | 640 × 427 | 39,228 |
| image 0.72.0 / Vix 0.42.0 | 8.17.3 | 640 × 427 | 39,228 |
尺寸、格式和“没有放大”是对齐的。字节数没有完全相同:sharp 的 libvips 比系统库新一个次版本;pyvips、CLI 与这次的 Image 共享 8.17.3,字节数相同,但与 govips 的缩略图调用路径仍有差异。字节数相同不等于像素相同。
继续阅读构建第一个完整图像 Pipeline,把输入检查、方向归一化、编码和结果验证拆成明确阶段。