Skip to content

Instantly share code, notes, and snippets.

@julianrubisch
Last active October 4, 2024 19:46
Show Gist options
  • Save julianrubisch/64af1d3bddaee6c53d386f4dd3e39695 to your computer and use it in GitHub Desktop.
Save julianrubisch/64af1d3bddaee6c53d386f4dd3e39695 to your computer and use it in GitHub Desktop.
Ruby Oneliners to convert images to webp and generate thumbnails
require 'fileutils'
# Loop through all .jpg and .png files in the current directory
Dir.glob("{*.jpg,*.png}").each do |img|
# Construct the output filename with .webp extension
output_filename = "#{File.basename(img, File.extname(img))}.webp"
# Execute ffmpeg command to convert the image
system("ffmpeg -i '#{img}' '#{output_filename}'")
end
ruby -e "Dir.glob('{*.jpg,*.png}').each { |img| system('ffmpeg -i \'' + img + '\' -q:v 80 \'' + File.basename(img, File.extname(img)) + '.webp\'') }"
require 'fileutils'
# Loop through all .jpg and .png files in the current directory
Dir.glob("{*.jpg,*.png,*.webp}").each do |img|
# Use ffprobe to get the original image width
original_width = %x(ffprobe -v error -select_streams v:0 -show_entries stream=width -of default=noprint_wrappers=1:nokey=1 "#{img}").to_i
# Calculate new widths for medium and small sizes
medium_width = original_width / 2
small_width = original_width / 3
# Base filename without extension
basename = File.basename(img, File.extname(img))
# Convert and resize to medium
system("ffmpeg -i '#{img}' -vf scale=#{medium_width}:-1 '#{basename}.medium.webp'")
# Convert and resize to small
system("ffmpeg -i '#{img}' -vf scale=#{small_width}:-1 '#{basename}.small.webp'")
end
ruby -e 'Dir.glob("{*.jpg,*.png,*.webp}").each do |img| width = %x(ffprobe -v error -select_streams v:0 -show_entries stream=width -of default=noprint_wrappers=1:nokey=1 "#{img}").to_i; medium_width = width / 2; small_width = width / 3; basename = File.basename(img, File.extname(img)); system("ffmpeg -i \"#{img}\" -vf scale=#{medium_width}:-1 \"#{basename}.medium.webp\""); system("ffmpeg -i \"#{img}\" -vf scale=#{small_width}:-1 \"#{basename}.small.webp\""); end'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment