Skip to content

Instantly share code, notes, and snippets.

@zjrosen1
Created November 5, 2013 19:02
Show Gist options
  • Save zjrosen1/7324247 to your computer and use it in GitHub Desktop.
Save zjrosen1/7324247 to your computer and use it in GitHub Desktop.
Ruby script for optimizing images
#!/usr/bin/ruby
# Instructions
# - Install optipng + libjpeg (http://mxcl.github.com/homebrew/)
# - Put this file in a directory of images
# - run with $ ruby optimize_images.rb
# Config
dir = File.dirname(__FILE__)
optipng = "/usr/local/bin/optipng"
jpegtran = "/usr/local/bin/jpegtran"
png = ".png"
jpg = ".jpg"
suffix = "-opt"
replace = true
# Optimize PNGs
p "Optimizing .pngs in #{dir}"
Dir.glob(dir + "/**/*#{png}").each do |f|
d = File.dirname(f)
n = "#{File.basename(f,File.extname(f))}#{suffix}#{png}"
o = "#{d}/#{n}"
if replace
p "- #{f}"
`#{optipng} #{f}`
else
p "- #{f} > #{o}"
`#{optipng} #{f} -out #{o}`
end
end
# Optimize JPGs
p "Optimizing .jpgs in #{dir}"
Dir.glob(dir + "/**/*#{jpg}").each do |f|
d = File.dirname(f)
n = "#{File.basename(f,File.extname(f))}#{suffix}#{jpg}"
o = "#{d}/#{n}"
if replace
p "- #{f}"
`#{jpegtran} -optimize #{f}`
else
p "- #{f} > #{o}"
`#{jpegtran} -optimize -outfile #{o} #{f}`
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment