Skip to content

Instantly share code, notes, and snippets.

@Coro365
Last active March 28, 2020 12:47
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 Coro365/f20a09db628713461ad1d1c14113da12 to your computer and use it in GitHub Desktop.
Save Coro365/f20a09db628713461ad1d1c14113da12 to your computer and use it in GitHub Desktop.
Adding margins to an image to make it square. (ImageMagick)
def add_margin_for_square
images = get_files_from_ARGV
images.each_with_index do |file, i|
puts("[#{i}/#{images.size}]\t#{file}")
size = get_width_hight(file)
margin = margin(size)
if margin.first.zero?
puts("#{file} is square")
# TODO: create file-squre.jpg
else
add_margin(file, mini(size), margin)
end
end
end
def get_files_from_ARGV(recursive: true)
files = ARGV.map do |path|
path = File.expand_path(path)
if File.directory?(path)
if recursive
Dir.glob(File.join(path, '**', '*'))
else
Dir.glob(File.join(path, '*'))
end
elsif File.file?(path)
path
else
puts("Not exists file: #{path}")
end
end
raise('ARGV empty') if ARGV.empty?
files.flatten.compact.sort.reject { |e| File.directory?(e) }
end
def get_width_hight(file)
file_escape = file.gsub(/\&\(\)\{\}\[\]\*\?\!\|\\\ \':/) { |c| '\\' + c }
result = `identify -format "%w %h" #{file_escape}`
width, *_garbage, hight = result.split("\s").map(&:to_i)
{width: width, hight: hight}
end
def margin(size)
diff = (size[:width] - size[:hight]).abs
margin = diff / 2
if (diff % 2).zero?
[margin, margin]
else
[margin + 1, margin]
end
end
def mini(size)
size.key(size.values.min).to_s
end
def add_margin(file, mini, margin)
file_e = file.gsub(/\&\(\)\{\}\[\]\*\?\!\|\\\ \':/) { |c| '\\' + c }
dir = File.dirname(file_e)
file_name = File.basename(file_e, '.*') + '-square' + File.extname(file_e)
new_file_e = File.join(dir, file_name)
cmd = ['convert', file_e, cmd_opt(mini, margin), new_file_e].flatten
system(*cmd)
end
def cmd_opt(mini, margin)
if mini == 'hight'
['-gravity', 'north', '-splice', "0x#{margin[0]}",
'-gravity', 'south', '-splice', "0x#{margin[1]}"]
else
['-gravity', 'west', '-splice', "#{margin[0]}x0",
'-gravity', 'east', '-splice', "#{margin[1]}x0"]
end
end
add_margin_for_square
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment