LoginSignup
2
2

More than 5 years have passed since last update.

dataURIを作る

Posted at

data uri schemeを手作業で作ってもそれほど面倒じゃない。
でも、コピペやAlt+Tab が多くて嫌になるので、コマンドにした

base64_embed_datauri.rb
#!/usr/bin/env ruby

require 'base64'
require 'rubygems'
require 'mime/types'
require 'optparse'

##初期化
with=nil
####引数処理
opt = OptionParser.new
opt.on(
    "--tag=[TAG]",
    "タグに埋め込んだ状態で出力する.デフォルト<img>(MIME判別) ")
    {|arg| 
        case arg
            when nil
                with = "img"
            when false
                with = false
            else
                with = arg
        end
    }

opt.on("--css", "CSS埋め込み用に展開する .url(\"data:image/png;base64,XXXX\") "){ |arg| with = "css"|| arg if arg }
opt.parse!(ARGV)

###メイン処理
data_type =  MIME::Types.type_for(ARGF.path).first.to_s
if with != false then
    with = "script" if data_type =~/script/i
    with = "img"    if data_type =~/image/i
    #with = "embed"  if data_type =~/flash/i # no browser support swf in data uri scheme
    with = "svg"    if data_type =~/svg/i
end

data_str  =  Base64.encode64(ARGF.read).gsub /\n/,""
src_str =  "data:#{data_type};base64,#{data_str}"
##出力処理
case with
    when "img"
        puts "<img src=\"#{src_str}\" />"
    when "script"
        puts "<script src=\"#{src_str}\"></script>"
    when "css"
        puts "url(\"#{src_str}\""
    when "object"
        puts "<object data='#{src_str}' type='#{data_type}'> </object>"
    when "embed"
        puts "<embed src='#{src_str}' type='#{data_type}' />"
    when false
        puts src_str
    else
        puts "<#{with} src=\"#{src_str}\" />"
end

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2