Skip to content

Instantly share code, notes, and snippets.

@Nereare
Created June 12, 2019 18:56
Show Gist options
  • Save Nereare/145662992eae3bf4d6e8e03bef402ae9 to your computer and use it in GitHub Desktop.
Save Nereare/145662992eae3bf4d6e8e03bef402ae9 to your computer and use it in GitHub Desktop.
Convert image files into their base64 strings from the command line, with each argument being a different single file.
require 'base64'
if ARGV.length > 0
#To64Html.new(ARGV[0]).html()
ARGV.each do |arg|
puts "Enconding file: " + arg.to_s
img = File.open(arg, 'rb')
encoded = 'data:image/png;base64,' + Base64.encode64(img.read).gsub(/\n/m, "")
enfile = arg.gsub(/\.png|jpg|jpeg|gif/, ".txt")
File.open(enfile, 'w:UTF-8') { |file| file.write(encoded) }
puts "Saved encoded image to: " + enfile
encoded_size = (File.size(enfile).to_f / 2**20).round(2)
image_size = (File.size(arg).to_f / 2**20).round(2)
puts " --> Size: " + encoded_size.to_s + "MB, Base64/image ratio: " + (encoded_size * 100.0 / image_size).round(2).to_s + "%"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment