Last active
October 29, 2024 13:10
-
-
Save pvdb/f3a8f7c1669af21b1a68b561c79ef386 to your computer and use it in GitHub Desktop.
convert images to "squared" PNGs
This file contains hidden or 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 | |
# 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 | |
border = ENV.fetch('BORDER', '0').to_i | |
next if width == height && border.zero? | |
size = [width, height].max + border | |
# | |
# for transparent background: | |
# | |
# -background \"rgba(0,0,0,0)\" | |
# | |
background = ENV.fetch('BG', 'white') | |
cmd = <<~"EOCMD".gsub(?\n, ' ') | |
magick | |
-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