18

I've read through man pngcrush and it seems that there is no way to crush a PNG file and save it over the original. I want to compress several folders worth of PNGs so it would be useful to do it all with one command!

Currently I am doing pngcrush -q -d tmp *.png then manually cut-pasting the files from the tmp directory to the original folder. So I guess using mv might be the best way to go? Any better ideas?

2 Answers 2

30

Since version 1.7.22, pngcrush has an overwrite option.

Try

pngcrush -ow file.png

See Changelog for more information:

Version 1.7.22  (built with libpng-1.5.6 and zlib-1.2.5)
  Added "-ow" (overwrite) option.  The input file is overwritten and the
    output file is just used temporarily and removed after it is copied
    over the input file..  If you do not specify an output file, "pngout.png"
    is used as the temporary file. Caution: the temporary file must be on
    the same filesystem as the input file.  Contributed by a group of students
    of the University of Paris who were taking the "Understanding of Programs"
    course and wished to gain familiarity with an open-source program.
1
  • When I was using the -ow option to do bulk processing images, e.g with for file in *.png; do ..., I had issues where the final images had been mixed up (some files where replaced with a crushed version of a completely different file). I suspect this was some kind of race condition where the temporary "pngout.png" file was reused before the system finalised copying it back over the original file. To solve this, generate a unique outfile to prevent pngcrush from using the same temporary file for each operation, e.g pngcrush -ow "$file" "${file%.png}-crushed.png"
    – Nicholas
    Nov 8, 2023 at 22:54
17

All on one line:

for file in *.png; do pngcrush "$file" "${file%.png}-crushed.png" && mv "${file%.png}-crushed.png" "$file"; done

should do it.

(Though so far in my own tests, less than half of the pngs I tested pngcrush on were smaller afterwards, so color me unimpressed.)

4
  • Thanks! The amount you can compress the PNGs can depend on how they were made. I believe Photoshop's "Save for Web" has some form of PNG crusher built in. Feb 17, 2011 at 10:40
  • Most of mine were created with ImageMagick's import command. I avoid commercial software like Photoshop whenever possible.
    – frabjous
    Feb 17, 2011 at 17:45
  • 4
    use -brute for better compression. Aug 7, 2012 at 3:00
  • 2
    The other answer is now better with newer pngcrush.
    – Hugo
    Oct 19, 2015 at 7:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .