Created
August 29, 2022 21:20
-
-
Save derat/ff6376df2e0024631e632ffd3346d06b to your computer and use it in GitHub Desktop.
Ruby script to resize images using ImageMagick's convert program
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/ruby | |
require 'optparse' | |
require 'shellwords' | |
def die(msg) | |
$stderr.puts msg | |
exit 1 | |
end | |
scale = nil | |
new_height = nil | |
new_width = nil | |
quality = nil | |
o = OptionParser.new | |
o.banner = "Usage: resize_image [options] OLD_FILE NEW_FILE" | |
o.on('-h', '--height=HEIGHT', 'Resize height in pixels') {|v| new_height = v.to_i } | |
o.on('-s', '--scale=SCALE', 'Resize scale as (0.1, 1.0]') {|v| scale = v.to_f } | |
o.on('-w', '--width=WIDTH', 'Resize width in pixels') {|v| new_width = v.to_i } | |
o.on('-q', '--quality=QUALITY', 'JPEG quality as [0, 100]') {|v| quality = v.to_i } | |
args = o.parse(*ARGV) | |
args.size == 2 || die(o.help) | |
actions = (scale ? 1 : 0) + (new_width ? 1 : 0) + (new_height ? 1 : 0) | |
if actions == 0 | |
scale = 1 | |
elsif actions > 1 | |
die("Set either --scale, --width, or --height") | |
end | |
old_file, new_file = args | |
die("#{old_file} doesn't exist") if !File.exists?(old_file) | |
out = `identify -format "%w %h\n" -ping "#{old_file}"` | |
parts = out.split(' ') | |
die("Unable to get dimensions") if parts.size != 2 | |
old_width, old_height = parts.map {|p| p.to_i } | |
if scale | |
new_width = (old_width * scale).round.to_i | |
new_height = (old_height * scale).round.to_i | |
elsif new_width | |
scale = new_width.to_f / old_width | |
new_height = (old_height * scale).round.to_i | |
else # new_height | |
scale = new_height.to_f / old_height | |
new_width = (old_width * scale).round.to_i | |
end | |
puts "#{old_file} (#{old_width}x#{old_height}) -> #{new_file} (#{new_width}x#{new_height})" | |
cmd = "convert #{Shellwords.escape(old_file)} " + | |
"-colorspace RGB " + | |
"-resize #{new_width}x#{new_height} " + | |
(quality ? "-quality #{quality} " : "") + | |
Shellwords.escape(new_file) | |
system(cmd) || die("Failed to run #{cmd}") | |
puts "#{File.size(old_file)} -> #{File.size(new_file)} bytes" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment