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 comment:

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