Skip to content

Instantly share code, notes, and snippets.

@stamat
Created September 12, 2022 14:41
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 stamat/cf11790f1b0c657f46de851b4ad35c4e to your computer and use it in GitHub Desktop.
Save stamat/cf11790f1b0c657f46de851b4ad35c4e to your computer and use it in GitHub Desktop.
Ruby script for batch image resize and optimisation
#!/usr/bin/env ruby
# frozen_string_literal: true
# brew install imagemagick advancecomp gifsicle jhead jpegoptim jpeg optipng pngcrush pngquant jonof/kenutils/pngout
# gem install mini_magick image_optim image_optim_pack
# Usage: ./imagebatch.rb [src_dir] [dest_dir] [resize="200x200"] [format="jpg"]
require "mini_magick"
require "image_optim"
def single(file_path, dest_path = nil, resize = nil, format = nil)
image_optim = ImageOptim.new({
:svgo => false,
:oxipng => false
})
filename = file_path.match(/[^\/\\]+$/)[0]
image = MiniMagick::Image.open(file_path)
image.resize resize if resize
if dest_path.nil?
dest_path = file_path
else
dest_path = File.join(dest_path, filename)
end
if format
image.format format
dest_path = dest_path.gsub(/\.png|\.jpe?g|\.webp|\.gif$/i, ".#{format}")
image.write dest_path
File.delete(file_path)
end
puts dest_path
image_optim.optimize_image!(dest_path)
end
def all(src_path, dest_path = nil, resize = nil, format = nil)
dest_path = src_path if dest_path.nil?
Dir.foreach(src_path) do |file|
next if !/\.png|\.jpe?g|\.webp|\.gif$/i.match(file)
file_path = File.join(src_path, file)
single(file_path, dest_path, resize, format)
end
end
def single_command(file_path, *args)
single(file_path, *args)
end
def all_command(src_path, *args)
all(src_path, *args)
end
fn_index = {
"single" => method(:single_command),
"all" => method(:all_command)
}
fn_index[ARGV[0]].call(ARGV[1], ARGV[2], ARGV[3], ARGV[4])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment