Thursday, October 15, 2009

Crushing PNGs With Ruby

Nothing too special here... just a quick hack. I needed to recursively run pngcrush over a directory structure, and I couldn't find any examples of how to do this online. The following solves the problem nicely. Hopefully someone else finds this helpful.

require 'fileutils'
require 'find'

input_dir = ARGV[0]
rewrite_dir = "/tmp/crush/"

raise("Usage #{$0} dirname") unless input_dir
Dir.mkdir(rewrite_dir) unless test(?d, rewrite_dir)

Find.find(input_dir) do |file|
  if file =~ /\.png$/
    base_dir = File.dirname(file)
    base_file = File.basename(file)
    new_dir = rewrite_dir + base_dir
    FileUtils.mkdir_p(new_dir) unless test(?d, new_dir)
    puts(%Q!pngcrush -reduce -brute "#{file}" "#{new_dir}/#{base_file}"!)
From there, you can just do something like: crush.rb images | sh.


  1. mkdir /tmp/crush; find . -type f -iname *\.png -exec pngcrush -reduce -brute -d /tmp/crush {} \;

  2. Excellent blog, I wish to share your post with my folks circle. It’s really helped me a lot, so keep sharing post like this
    Selenium Training in Chennai | Selenium Training in Bangalore | Selenium Training in Pune