Skip to content

Instantly share code, notes, and snippets.

@brandur
Created March 10, 2020 17:57
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 brandur/5f1c264972a5ee3cf1e17fe2241454f4 to your computer and use it in GitHub Desktop.
Save brandur/5f1c264972a5ee3cf1e17fe2241454f4 to your computer and use it in GitHub Desktop.
Image resize and optimize script
#!/usr/bin/env ruby
#
# Downsizes and optimizes (for size) an image so that it can be suitably/easily
# sent to people via email.
#
TARGET_DIR = "#{Dir.home}/Downloads"
TARGET_WIDTH = 2000
#
# ---
#
CACHED_HOMEBREW_PATHS = {}
def get_homebrew_path(package)
CACHED_HOMEBREW_PATHS[package] ||= begin
brew_path = run_command("brew --prefix #{package}", abort: false)
if !brew_path
abort("Homebrew package #{package} may be unavailable; try `brew install #{package}`")
end
brew_path
end
end
def run_command(command, abort: true)
ret = `#{command}`
if $? != 0
if abort
abort("command failed: #{command}")
else
return false
end
end
ret.strip
end
#
# ---
#
def main
unless Dir.exists?(TARGET_DIR)
abort("Target dir does not exist: #{TARGET_DIR}")
end
magick_path = get_homebrew_path("imagemagick")
mozjpeg_path = get_homebrew_path("mozjpeg")
abort("need at least one file as argument") if ARGV.empty?
ARGV.each do |filename|
width, height =
run_command(%{#{magick_path}/bin/magick convert #{filename} -format "%[w] %[h]" info:}).
split
target_proportion = if width > height
"#{TARGET_WIDTH}x" # landscape
else
"x#{TARGET_WIDTH}" # portrait
end
target_filename = "#{TARGET_DIR}/#{File.basename(filename, ".*")}.jpg"
run_command("#{magick_path}/bin/magick convert #{filename} -resize #{target_proportion} -quality 85 JPEG:- | #{mozjpeg_path}/bin/cjpeg -outfile #{target_filename} -optimize -progressive")
puts "Created: #{target_filename}"
end
end
#
# ---
#
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment