Skip to content

Instantly share code, notes, and snippets.

@dekart
Created August 9, 2013 09:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dekart/6192335 to your computer and use it in GitHub Desktop.
Save dekart/6192335 to your computer and use it in GitHub Desktop.
A script to convert JPEG and PNG images in desired folders to WebP
#!/usr/bin/env ruby
def process_folders(message, *folders, &block)
root = File.expand_path('../..', __FILE__)
puts message
puts
total_old = 0
total_new = 0
folders.map{|f| Dir[File.join(root, f)] }.flatten.sort.each do |file|
old_size, new_size = yield(file)
next unless old_size && new_size
puts "%70s: %7d -> %7d (%0.1f%% less)" % [
file.sub(root, ''),
old_size,
new_size,
(1 - new_size.to_f / old_size) * 100
]
if old_size > new_size
total_old += old_size
total_new += new_size
end
end
puts
puts "Done! Total save: %d of %d (%01.f%%)" % [
total_old - total_new,
total_old,
(1 - total_new.to_f / total_old) * 100
]
puts
end
process_folders("Converting PNG images to WebP...",
'public/assets/**/*.png',
'public/images/**/*.png'
) do |file|
next if File.file?("#{file}.webp") && File.mtime("#{file}.webp") > File.mtime(file)
result = `cwebp -short -alpha_method 1 -lossless #{ file } -o #{ file }.webp 2>&1`
old_size = File.size(file)
new_size = result.split(' ').first.to_i
[old_size, new_size]
end
process_folders("Converting JPG images to WebP...",
'public/assets/**/*.jpg',
'public/images/**/*.jpg'
) do |file|
next if File.file?("#{file}.webp") && File.mtime("#{file}.webp") > File.mtime(file)
result = `cwebp -short #{ file } -o #{ file }.webp 2>&1`
old_size = File.size(file)
new_size = result.split(' ').first.to_i
[old_size, new_size]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment