メインコンテンツまでスキップ

svg-to-png spec

  • 作成:
  • 更新:
  • 著者:
    Takeshi Takatsudo

Overview

svg-to-png converts kumiko-gen SVG thumbnails to 1200x630 PNG images for OGP (Open Graph Protocol) / social media previews. Located at sub-packages/svg-to-png/. Uses sharp for SVG rasterization.

Input: SVG file (square, typically 800x800). Output: PNG buffer (1200x630, center-cropped).

Conversion pipeline

  1. Read SVG file from blog/public/thumbnails/{slug}.svg
  2. Rasterize SVG at 1200x1200 (150 DPI, fit: 'fill')
  3. Center-crop: remove 285px from top and 285px from bottom → 1200x630
  4. Encode as PNG
  5. Write to blog/public/thumbnails/{slug}.png

All operations execute in a single sharp pipeline (no intermediate buffer).

Center-crop math

The input SVG is square (1:1 ratio). The output is landscape (1200:630 ≈ 1.905:1).

renderSize = width = 1200
cropTop = Math.round((width - height) / 2) = Math.round((1200 - 630) / 2) = 285
cropBottom = 285 (symmetric)
extract: { left: 0, top: 285, width: 1200, height: 630 }

The crop is always symmetric — equal amounts removed from top and bottom.

Options

interface ConvertOptions {
width?: number; // output width in px (default: 1200)
height?: number; // output height in px (default: 630)
}

Custom dimensions must satisfy height <= width (landscape or square). The SVG is always rendered at width x width then cropped to width x height.

API

// Convert SVG buffer to PNG buffer
convertSvgToPng(svgBuffer: Buffer, options?: ConvertOptions): Promise<Buffer>

// Convert SVG file to PNG buffer (with file-existence check)
convertSvgFileToPng(inputPath: string, options?: ConvertOptions): Promise<Buffer>

Both exported from svg-to-png package.

CLI

pnpm svg-to-png <slug> [options]
FlagDescription
--out <path>Custom output file path
--allConvert all SVGs in the thumbnails directory

Single file

pnpm svg-to-png my-article
# Reads: blog/public/thumbnails/my-article.svg
# Writes: blog/public/thumbnails/my-article.png

Batch conversion

pnpm svg-to-png --all
# Converts all *.svg files in blog/public/thumbnails/ to *.png

Dependencies

  • sharp (^0.33.0) — SVG rasterization and image processing via libvips

File structure

sub-packages/svg-to-png/
├── src/
│ ├── index.ts # Public exports
│ ├── cli.ts # CLI entry
│ └── converter.ts # Core: SVG buffer → PNG buffer
├── test/
│ └── converter.test.ts
├── package.json
└── tsconfig.json