Compress images to speed up your website


Everyone has heard that you need to compress images on your website to get the best performance, but not everyone knows how. There are a number of programs that can help. If you use linux, I would suggest:

  • pngcrush for png
  • jpegtran for jpeg
  • gifsicle for gif

Debian & Ubuntu both have packages for all 3. Combine with the following script and you are moments away from better site performance:

#!/usr/bin/ruby
require 'find'

Find.find( ARGV[0] ) do | file |
  if file.match( '\.gif$' )
    command = sprintf( 'gifsicle --batch -O2 %s', file )
    puts command
    system( command )
  end
  if file.match( '\.jpe?g$' )
    command = sprintf( 'jpegtran -copy none -optimize -outfile %s %s', file, file )
    puts command
    system( command )
  end
  if file.match( '\.png$' )
    new_file = "#{file}-crushed"
    command = sprintf( 'pngcrush -q -rem alla -brute -reduce %s %s', file, new_file )
    puts command
    system( command )
    if File.exists?( new_file )
      if File.size( new_file) < File.size( file )
        command = "mv #{new_file} #{file}"
      else
        command = "rm #{new_file}"
      end
      puts command
      system( command )
    end
  end
end

Just pass the local filesystem root of your website to the script and it will compress all gif, jpeg and png images that it finds within the website hierarchy.