Skip to content

Instantly share code, notes, and snippets.

@gaborbata
Last active December 20, 2023 07:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gaborbata/1b495bae1bb708c7e5b562d83580078f to your computer and use it in GitHub Desktop.
Save gaborbata/1b495bae1bb708c7e5b562d83580078f to your computer and use it in GitHub Desktop.
Convert images recursively to webp
#!/usr/bin/env ruby
# Convert images recursively to webp
require 'fileutils'
CONVERTERS = {
'cwebp' => '-q 80 "%s" -m 6 -o "%s"',
'magick convert' => '-quality 80 -define webp:method=6 "%s" "%s"'
}
converter = CONVERTERS.find { |cmd, params| system("#{cmd} -version") }
Dir.glob('**/*.{jpg,png,JPG}').each do |image|
webp_img = image.sub(/\.(jpg|png|JPG)$/, '.webp')
if converter && !File.exist?(webp_img)
mtime = File.mtime(image)
success = system("#{converter[0]} #{sprintf(converter[1], image, webp_img)}")
FileUtils.touch(webp_img, :mtime => mtime) if success
system("rm \"#{image}\"") if success
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment