Skip to content

Instantly share code, notes, and snippets.

@pvdb
Last active March 12, 2024 12:36
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 pvdb/f3a8f7c1669af21b1a68b561c79ef386 to your computer and use it in GitHub Desktop.
Save pvdb/f3a8f7c1669af21b1a68b561c79ef386 to your computer and use it in GitHub Desktop.
convert images to "squared" PNGs
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# INSTALLATION
#
# ln -s ${PWD}/square_fit $(brew --prefix)/bin/
# sudo ln -s ${PWD}/square_fit /usr/local/bin/
#
# PREREQUISITES
#
# brew install media-info
# brew install imagemagick
#
require 'json'
# rubocop:disable Style/BlockDelimiters
# rubocop:disable Style/CharacterLiteral
ARGV.each do |input|
next unless File.size? input
output = input.gsub(/#{File.extname(input)}\z/, '_squared.png')
next if File.size? output
mediainfo = JSON.parse(`mediainfo --Output=JSON \"#{input}\"`)
image_track = mediainfo['media']['track'].find { |track|
track['@type'] == 'Image'
}
next unless image_track
width = image_track['Width'].to_i
height = image_track['Height'].to_i
next if width == height
size = [width, height].max
border = ENV.fetch('BORDER', '0').to_i
size += border
background = ENV.fetch('BG', 'white')
#
# for transparent background:
#
# -background \"rgba(0,0,0,0)\"
#
cmd = <<~"EOCMD".gsub(?\n, ' ')
convert
-define png:size=\"#{size}x#{size}\"
\"#{input}\"
-background #{background}
-gravity center
-extent \"#{size}x#{size}\"
\"#{output}\"
EOCMD
system(cmd)
end
# rubocop:enable Style/CharacterLiteral
# rubocop:enable Style/BlockDelimiters
# That's all Folks!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment