Created
May 15, 2023 18:35
-
-
Save tonyedwardspz/f0f821ceac27c9a6e7cd48fa24b88a4e to your computer and use it in GitHub Desktop.
Resize images and convert to .jpg, deleting the original files.
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 | |
require 'mini_magick' | |
require 'fileutils' | |
begin | |
size = Integer(ARGV[0]) | |
rescue ArgumentError | |
puts "Size argument must be an integer." | |
exit | |
end | |
image_files = Dir.glob("*.{jpg,png,gif}") | |
total_images = image_files.count | |
resized_images = 0 | |
total_starting_size = image_files.reduce(0) { |sum, file| sum + File.size(file) } | |
total_ending_size = 0 | |
image_files.each do |image_file| | |
image = MiniMagick::Image.open(image_file) | |
# Resize the image, retaining the aspect ratio | |
if image[:width] > size | |
image.resize "#{size}x" | |
resized_images += 1 | |
end | |
image.quality 85 | |
new_file = image_file.sub(/\.[^.]+\z/, '.jpg') | |
image.format 'jpg' | |
image.write new_file | |
total_ending_size += File.size(new_file) | |
File.delete(image_file) | |
end | |
puts "Total images processed: #{total_images}" | |
puts "Total images resized: #{resized_images}" | |
puts "Total starting size: #{(total_starting_size / 1024.0).round(2)} KB" | |
puts "Total ending size: #{(total_ending_size / 1024.0).round(2)} KB" | |
puts "Saved: #{((total_starting_size - total_ending_size) / 1024.0).round(2)} KB" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment