Skip to content

Instantly share code, notes, and snippets.

@sunny
Created October 28, 2008 15:59
Show Gist options
  • Save sunny/20410 to your computer and use it in GitHub Desktop.
Save sunny/20410 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby -W0
# Crush!
# Crushes png and jpg images by removing their headers and usually unnessecary data for the web.
# Needs pngcrush and jpegtran.
#
# Usage:
# $ crush directory/to/copy new/directory
#
# Installing pngcrush and jpegtran under OS X:
# $ sudo port install pngcrush
#
# $ cd /tmp
# $ curl http://txfx.net/files/osx/automatic-lossless-jpg-rotation-for-os-x.zip > jhead-jpegtran.zip
# $ unzip jhead-jpegtran.zip
# $ sudo cp Automatic\ Lossless\ Photo\ Rotation/jpegtran /usr/bin/
# $ rm -fr jhead-jpegtran.zip Automatic\ Lossless\ Photo\ Rotation
#
# Author: Sunny Ripert <sunfox.org>
# Licence: WTFPL
require 'fileutils'
require 'tempfile'
include FileUtils
# Find directories in which to work
dir = ARGV[0]
abort "Usage: #{File.basename($0)} dir" if dir.nil?
# Find all files
files = []
cd(dir) do
search = File.join('**', '*')
files = Dir[search]
end
abort "No files found in #{dir}" if files.empty?
tmp_file = Tempfile.new('current_image').path
files.each do |file|
old_file = File.expand_path(File.join(dir, file))
next if File.directory?(old_file)
case file
when /\.png$/
# Try pngcrush
`pngcrush '#{old_file}' '#{tmp_file}'`
if $?.exitstatus == 0
cp tmp_file, old_file
next
end
# Try optipng
`optipng '#{old_file}'`
when /\.jpe?g$/
# Try jpegtran
#`jpegtran -copy none -optimize -perfect #{file} #{tmp_file}`
`jpegtran -copy none -optimize '#{old_file}' > '#{tmp_file}'`
cp tmp_file, old_file if $?.exitstatus != 0
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment