pngtruncate

#!/bin/sh
# truncates a progressive PNG image, outputs degraded copy on standard output
# first parameter: input filename; second parameter: number of scans in output
SCANS=$2;
CHUNK_COUNT=$(grep -c IDAT <$1);
FRACTION=$(echo 2 7 $SCANS - ^ p | dc); # Adam7 fractions
CHUNKS_TARGET=$(echo $CHUNK_COUNT $FRACTION / 1 + p | dc);
SIZE_TARGET=$(
  echo $(
    (grep -abo IDAT <$1; echo $(echo $(wc -c <$1) 4 + p | dc ):IDAT) |\
    head -n$(echo $CHUNKS_TARGET 1 + p | dc) | tail -n1 | cut -d: -f1;
  ) 4 - p | dc
);
head -c"$SIZE_TARGET" <"$1";
# Adding an IEND chunk causes Mozilla to not display the image.
# env printf '\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82';