You need to enable JavaScript to run this app. 如何使用pngquant批量处理PNG文件夹并在目标目录保留原目录结构
优惠活动
大模型
产品
解决方案
定价
更多

如何使用pngquant批量处理PNG文件夹并在目标目录保留原目录结构

调整后的pngquant批量压缩脚本实现方案

你当前的脚本是直接在原目录下修改文件,只需要新增路径映射、自动创建目标目录的逻辑即可实现输出到新目录并保留原结构的需求,以下是适配你环境的可用脚本:

Shell版本(适用于Windows下的Git Bash/WSL等Shell环境)

# 自定义配置项,根据实际路径修改
SRC_ROOT="C:/FOLDER"
DEST_ROOT="C:/COMPRESSED_PNG"
PNGQUANT_PATH="path/to/pngquant.exe"

# 遍历源目录下所有PNG文件
find "$SRC_ROOT" -type f -name "*.png" | while read -r src_png; do
    # 提取文件相对于源根目录的相对路径
    rel_path="${src_png#$SRC_ROOT/}"
    # 拼接目标文件的完整路径
    dest_png="$DEST_ROOT/$rel_path"
    # 自动创建目标文件所属的父目录,不存在则新建
    mkdir -p "$(dirname "$dest_png")"
    
    # 调用pngquant压缩,直接输出到目标路径,不修改原文件
    "$PNGQUANT_PATH" --force 2 "$src_png" --output - > "$dest_png"
done

如果你的pngquant 2.0版本不支持--output -参数,改用以下逻辑:

# 自定义配置项,根据实际路径修改
SRC_ROOT="C:/FOLDER"
DEST_ROOT="C:/COMPRESSED_PNG"
PNGQUANT_PATH="path/to/pngquant.exe"

find "$SRC_ROOT" -type f -name "*.png" | while read -r src_png; do
    rel_path="${src_png#$SRC_ROOT/}"
    dest_png="$DEST_ROOT/$rel_path"
    mkdir -p "$(dirname "$dest_png")"
    
    # 生成临时压缩文件
    "$PNGQUANT_PATH" --ext .tmp.png --force 2 "$src_png"
    # 将临时文件移动到目标路径
    mv "${src_png%.png}.tmp.png" "$dest_png"
done

PowerShell版本(适用于Windows原生PowerShell环境)

如果你更习惯用Windows原生的PowerShell,可以使用以下脚本:

# 自定义配置项,根据实际路径修改
$srcRoot = "C:\FOLDER"
$destRoot = "C:\COMPRESSED_PNG"
$pngquantPath = "path\to\pngquant.exe"

Get-ChildItem -Path $srcRoot -Filter *.png -Recurse -File | ForEach-Object {
    $srcPng = $_.FullName
    $relPath = $srcPng.Substring($srcRoot.Length + 1)
    $destPng = Join-Path $destRoot $relPath
    $destDir = Split-Path $destPng -Parent
    # 自动创建缺失的目录
    if (-not (Test-Path $destDir)) {
        New-Item -ItemType Directory -Path $destDir | Out-Null
    }
    # 执行压缩
    & $pngquantPath --force 2 $srcPng --output - | Out-File $destPng -Encoding Byte
}

说明

  • 所有压缩后的文件都会保存在你指定的目标根目录下,目录结构和原C:\FOLDER完全一致,不会修改原目录的任何文件
  • 脚本默认遍历所有子目录的PNG文件,如果你需要限制遍历深度,可以给find命令加上-maxdepth N参数,PowerShell可以加上-Depth N参数

内容的提问来源于stack exchange,提问作者steepcurve

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 09:30:05