強火で進め

このブログではプログラム関連の記事を中心に書いてます。

CSSファイルに画像データを埋め込むツール「CSSEmbed」を使ってみた

ソースファイルを確認したところ、READMEに以下の様に記述してあり、data URIを使ってCSSに画像ファイルを埋め込むという仕組みの様です。

CSSEmbed is a small program/library to automate embedding of data URIs in
CSS files.

コンパイル済みのファイルはこちらからDLできます。

今回は cssembed-0.3.2.jar を使用しました。

使用方法はこちらのREADMEに記載があります。

Usage: java -jar cssembed-x.y.z.jar [options] [input file]

Global Options
  -h, --help            Displays this information.
  --charset <charset>   Character set of the input file.
  --mhtml               Enable MHTML mode.
  --mhtmlroot <root>    Use <root> as the MHTML root for the file.
  -v, --verbose         Display informational messages and warnings.
  --root <root>         Prepends <root> to all relative URLs.
  -o <file>             Place the output into <file>. Defaults to stdout.

テスト

今回、テストするために以下のファイルを同一フォルダに準備しました。

  • bg.jpg
  • test.css
  • test.html
  • test.css の内容
body {
  background-image: url("bg.jpg")
}
  • test.html の内容
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="test.css"> 
  </head>
  <body>
  </body>
</html>

実行したコマンドはこちら -o のオプションで出力ファイルの指定も可能ですが今回はリダイレクトを使用。

java -jar cssembed-0.3.2.jar test.css > test_embed.css

変換された出力ファイルの内容は以下

data:image/jpeg;base64,/9j/4W+eRXhpZgAASUkqAAgAAAAKAA8BAgAKAAA(以下省略)

ファイルサイズの比較

ファイル名 サイズ(Byte)
test.css 40
bg.jpg 165685
test_embed.css 220971

関連サイト

Data URIs for CSS Images: More Tests, More Questions - ravelrumba
http://www.ravelrumba.com/blog/data-uris-for-css-images-more-tests-more-questions/

A Look at How Browsers Download and Render CSS Background Images - ravelrumba
http://www.ravelrumba.com/blog/a-look-at-how-browsers-download-and-render-css-background-images/