Created
November 11, 2017 09:30
-
-
Save watzon/e111cd4ad9b7f3b5c24bd95a295db19f to your computer and use it in GitHub Desktop.
Resize an image to multiple sizes
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 'optparse' | |
require 'fileutils' | |
require 'mini_magick' | |
require 'pp' | |
options = { | |
output: '.', | |
format: '%n%-%s%' | |
} | |
OptionParser.new do |opts| | |
opts.on('-s', '--sizes a,b,c', Array, 'Set sizes') do |sizes| | |
options[:sizes] = sizes.map! { |s| s.split('x') } | |
options[:sizes].each { |a| a.push('') if a.size < 2 } | |
end | |
opts.on('-f', '--input [filename]', String, 'Input file') do |file| | |
options[:image] = file | |
end | |
opts.on('-o', '--output [directory]', String, 'Output directory') do |dir| | |
options[:output] = dir | |
end | |
opts.on('--format "%n%-%s%"', String, 'Format the filename should take') do |format| | |
options[:format] = format | |
end | |
end.parse! | |
if !options[:sizes] | |
puts "--sizes flag is required" | |
exit | |
elsif !options[:image] | |
puts "an input file is required" | |
exit | |
end | |
image = MiniMagick::Image.open(options[:image]) | |
ext, name = options[:image].split('/')[-1].split('.').reverse | |
unless File.directory?(options[:output]) | |
FileUtils.mkdir_p(options[:output]) | |
end | |
options[:sizes].sort! | |
options[:sizes].each do |(width, height)| | |
wh = height.empty? ? width.to_s : "#{width}x#{height}" | |
new_name = options[:format].gsub('%n%', name) | |
new_name = new_name.gsub('%s%', wh) | |
.gsub('%w%', width) | |
.gsub('%h%', height) | |
date_rgx = /%d{(.*)}%/ | |
if date_match = new_name.match(date_rgx) | |
formatted_date = DateTime.now.strftime(date_match[1]) | |
puts formatted_date.to_s | |
end | |
new_name = new_name + '.' + ext | |
output = File.join(options[:output], new_name) | |
image.resize "#{width}x#{height}" | |
image.write(output) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment