Skip to content

Instantly share code, notes, and snippets.

@Cairnarvon
Created May 8, 2012 00:20
Show Gist options
  • Save Cairnarvon/2631615 to your computer and use it in GitHub Desktop.
Save Cairnarvon/2631615 to your computer and use it in GitHub Desktop.
Data URI scheme encoder
#!/usr/bin/ruby -w
require 'optparse'
require 'base64'
options = {}
optparse = OptionParser.new do |opts|
opts.banner = "Usage: #$0 [options] FILE"
options[:type] = nil
opts.on('-m TYPE', '--mime TYPE', 'Specify MIME type') do |t|
options[:type] = t
end
options[:wrap] = 80
opts.on('-w COLS', '--wrap COLS', 'Wraps (default 80, 0 = no wrap)') do |w|
options[:wrap] = w.to_i
end
end
optparse.parse!
if ARGF.filename == '-'
STDIN.tty? && abort('No file specified!')
options[:type].nil? && abort('Cannot determine filetype!')
end
if options[:type].nil?
options[:type] = `file --mime -b #{ARGF.filename}`.chomp
end
out = "data:#{options[:type]};base64,"
out << Base64.encode64(ARGF.binmode.read).delete("\n")
options[:wrap] > 0 && out.gsub!(/.{#{options[:wrap]}}/, "\\0\n")
puts out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment