Last active
December 20, 2023 07:28
-
-
Save gaborbata/1b495bae1bb708c7e5b562d83580078f to your computer and use it in GitHub Desktop.
Convert images recursively to webp
This file contains 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 | |
# 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