Skip to content

Instantly share code, notes, and snippets.

@meinside
Last active May 3, 2022 08:14
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 meinside/5894116 to your computer and use it in GitHub Desktop.
Save meinside/5894116 to your computer and use it in GitHub Desktop.
generates in-line image tag (html)
#!/usr/bin/env ruby
# coding: UTF-8
# inline_image.rb
#
# generates in-line image tag
# (referenced: http://en.wikipedia.org/wiki/Data_URI_scheme)
#
# created on : 2013.06.30
# last update: 2013.06.30
#
# by meinside@duck.com
require "rubygems"
require "base64"
def print_usage
puts "* usage: #{__FILE__} [IMAGE_FILE_PATH]"
end
def image_file_type(filepath)
filemagic = ""
begin
if Gem::Specification.find_by_name "ruby-filemagic" # gem install ruby-filemagic
require "filemagic"
filemagic = FileMagic.new.file(filepath)
end
rescue
`which file`
if $?.exitstatus == 0
filemagic = `file "#{filepath}"`
else
raise "'filemagic' and 'file' are not installed"
end
end
case
when filemagic =~ /^jpeg image data/i
filemagic = "image/jpg"
when filemagic =~ /^gif image data/i
filemagic = "image/gif"
when filemagic =~ /^png image data/i
filemagic = "image/png"
else
filemagic = "application/octet-stream"
end
return filemagic
end
def generate_tag(filepath)
type = image_file_type(filepath)
base64 = ""
File.open(filepath, "r"){|f|
base64 = Base64.encode64(f.read).gsub("\n", "")
}
return "<img src=\"data:#{type};base64,#{base64}\" alt=\"#{File.basename(filepath)}\">"
end
if __FILE__ == $0
if ARGV.count < 1 || !(File.exists? File.expand_path(ARGV[0]))
print_usage
else
puts generate_tag(File.expand_path(ARGV[0]))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment