Batch PNG Conversion: A Safe CLI and Automation Workflow

November 08, 2026 · PNG.now Editorial · PNG Essentials

Design a repeatable PNG batch process with canaries, logs, validation and rollback.

Project Structure for Safe Batch Processing

png-batch/
├── sources/          # Input files (read-only)
├── processed/        # Output PNGs (write-once)
├── logs/             # Per-run JSONL + error dump
├── archive/          # Pre-conversion backups
├── quarantine/       # Unrecoverable files
├── canary.sh         # Pre-flight validation
├── convert.sh        # Main conversion driver
├── post_validate.sh  # PNG structural checks
└── rollback.sh       # Restore from archive

Never overwrite source files. processed/ is the only mutable target. This prevents data loss even if a script halts mid-run.

Canary Checks: Pre-Flight Validation

Before any conversion, run canary tests on a representative sample (minimum 10% of files or 50 images, whichever is smaller). This catches systemic issues early.

# canary.sh - exit codes: 0=pass, 1=warn, 2=fail
for f in sources/*; do
    # Test 1: File integrity (W3C PNG 3.0 §4.1)
    identify -verbose "$f" >/dev/null 2>&1 || echo "CORRUPT:$f"

    # Test 2: Color space compatibility (sRGB or grayscale only)
    COLOR=$(identify -format "%[colorspace]" "$f")
    [[ "$COLOR" == "sRGB" || "$COLOR" == "Gray" ]] || echo "UNSUPPORTED_COLORSPACE:$f:$COLOR"

    # Test 3: Bit depth ≤ 16 (per PNG spec §4.3.2)
    DEPTH=$(identify -format "%[bit-depth]" "$f")
    [ "$DEPTH" -le 16 ] || echo "OVER_DEPTH_LIMIT:$f:$DEPTH"
done

Canaries must fail hard. A warning exit code (1) means proceed but flag results; a fail (2) means abort the entire batch.

Conversion Pipeline with Structured Logging

Each file gets a JSON log entry recording source hash, conversion parameters, output size, and validation result. This enables post-hoc auditing without re-running.

#!/bin/bash
# convert.sh - idempotent per file
LOG_FILE="logs/$(date +%Y%m%d_%H%M%S).jsonl"
ARCHIVE_DIR="archive/$(basename "$LOG_FILE" .jsonl)"

mkdir -p "$ARCHIVE_DIR"

for src in sources/*; do
    filename=$(basename "$src")
    dest="processed/${filename%.*}.png"
    src_hash=$(sha256sum "$src" | cut -d' ' -f1)

    # Archive original before processing
    cp "$src" "$ARCHIVE_DIR/$filename"

    # Conversion with explicit PNG options (W3C spec §6.1)
    start_time=$(date +%s%N)
    convert "$src" -strip -set colorspace sRGB -depth 8 "$dest" 2>>logs/errors.txt
    exit_code=$?
    end_time=$(date +%s%N)
    duration=$(( (end_time - start_time) / 1000000 ))

    # Validation: check PNG signature (first 8 bytes per spec §4.1)
    signature_ok=$(head -c 8 "$dest" | od -An -tx1 | \
        grep -q "89 50 4e 47 0d 0a 1a 0a" && echo "true" || echo "false")

    # Structured log entry
    jq -n --arg f "$filename" --arg s "$src_hash" --arg d "$duration" \
       --arg e "$exit_code" --arg sig "$signature_ok" \
       '{file: $f, source_hash: $s, duration_ms: $d|tonumber,
         exit: $e|tonumber, signature_valid: $sig}' >> "$LOG_FILE"
done

Critical parameter: -strip removes all metadata except ICC profiles. Use -define png:exclude-chunks=all to strip ancillary chunks entirely. See W3C PNG 3.0 §5.2 for chunk classification.

Failure Tiers and Rollback Strategy

Three failure severities require distinct responses:

Severity Detection Point Action
Fatal Canary fails Abort batch, investigate source
Recoverable Conversion exit code ≠ 0 Retry once, log both attempts
Silent Signature invalid Flag for manual review, do not delete source

Rollback restores processed/ from archive/:

#!/bin/bash
# rollback.sh - atomic per file
ROLLBACK_ID=$1  # e.g., 20250321_143022
ARCHIVE_DIR="archive/$ROLLBACK_ID"

if [ -d "$ARCHIVE_DIR" ]; then
    for archived in "$ARCHIVE_DIR"/*; do
        filename=$(basename "$archived")
        dest="processed/${filename%.*}.png"
        if [ -f "$dest" ] && ! cmp -s "$archived" "$dest"; then
            cp "$archived" "$dest"
            echo "ROLLED BACK: $filename"
        fi
    done
fi

Post-Conversion Structural Validation

A converted PNG must pass three checks per the W3C reference:

  1. Signature verification ensures the file is a PNG, not a truncated JPEG renamed to .png.
  2. IHDR chunk integrity (W3C §4.1.1) – verify width, height, bit depth, color type, compression method, filter method, interlace method. Use pngcheck -v for this.
  3. CRC check – every chunk has a 4-byte CRC (W3C §3.4). pngcrush -n validates all CRCs without re-encoding.
# post_validate.sh - exit 0 only if all pass
for png in processed/*.png; do
    pngcheck -v "$png" >/dev/null 2>&1 || echo "FAIL: $png (chunk integrity)"
    pngcrush -n "$png" /dev/null 2>&1 | grep -q "CRC error" && echo "FAIL: $png (CRC)"
done

Automation Integration with Lockfile Guard

Wrap the pipeline in a state machine:

IDLE → CANARY → (fail? ABORT) → CONVERT → VALIDATE → (fail? ROLLBACK) → LOG → IDLE

Add a lockfile to prevent concurrent runs:

LOCKFILE=/tmp/png-batch.lock
exec 200>$LOCKFILE
flock -n 200 || { echo "Previous batch still running"; exit 1; }

Sample crontab entry:

*/30 * * * * /opt/png-batch/convert.sh 2>>/var/log/png-batch/cron.err

Unrecoverable Limits

No batch workflow can fix these conditions. Move affected files to quarantine/ and log the source hash:

  • Truncated files – missing IEND chunk (W3C §4.1.5)
  • Invalid IHDR dimensions – width=0 or height=0
  • Malformed PLTE palette – more than 256 entries (W3C §4.1.2)
  • Unknown critical chunks – chunk type with lowercase third byte (W3C §3.3)

Never attempt automatic repair on critical-chunk corruption. Only manual hex editing is viable, and only with a verified backup.

Log Analysis and Batch Reporting

Parse the JSONL log to generate a batch summary:

cat logs/*.jsonl | jq -s '
    {
        total: length,
        failures: map(select(.exit != 0 or .signature_valid == false)) | length,
        avg_duration: (map(.duration_ms) | add) / length,
        corrupt_sources: map(select(.signature_valid == false)) | map(.file)
    }'

Store summaries alongside raw logs. Archive logs with a retention policy (e.g., 90 days) to free disk space while preserving audit trails.

Technical basis for Batch PNG Conversion

Format-level claims use the primary PNG reference.