Created
August 9, 2013 09:18
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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