Convert PNG images to high-quality vector SVG, with support for removing white backgrounds.
Toolchain
PNG → magick (去白底+alpha阈值) → vtracer (样条曲线) → svgo (压缩) → SVG
- ImageMagick (
magick: Remove white background + alpha threshold processing - vtracer: Spline curve vectorization (smoother than potrace)
- svgo: SVG path compression optimization
How to invoke
When you need to convert PNG to SVG, follow these steps:
Input
INPUT_PNG: Input PNG file path (required)OUTPUT_SVG: Output SVG path (default: same name with .svg)KEEP_BG: Whether to keep the background (default: false, remove white background)
Execution steps
Step 1: Preprocessing (remove white background)
If the background needs to be removed (KEEP_BG=false):
magick INPUT_PNG \
-fuzz 15% -transparent white \
-channel A -threshold 50% +channel \
INPUT_PNG.temp.png
Step 2: Vectorization
vtracer --input INPUT_PNG.temp.png --output OUTPUT_SVG \
--mode spline \
--filter_speckle 8 \
--color_precision 8 \
--corner_threshold 120 \
--segment_length 6 \
--path_precision 5
Step 3: Compression optimization
npx svgo OUTPUT_SVG -o OUTPUT_SVG --multipass
Step 4: Cleanup
rm -f INPUT_PNG.temp.png
Output
Return the path of the generated SVG file, and report the file size.
✓ PNG → SVG 转换完成
输入: {INPUT_PNG}
输出: {OUTPUT_SVG}
大小: {file_size}
Dependencies
Before first use, make sure the following are installed:
brew install imagemagick
cargo install vtracer
npm install -g svgo # 或使用 npx
Parameter tuning
| Parameter | Effect | Effect of increasing |
|---|---|---|
filter_speckle |
Filter small spots | Cleaner |
corner_threshold |
Corner threshold | Smoother |
segment_length |
Line segment length | Smoother |
color_precision |
Color precision | More accurate |