RMagickで画像をHTMLに変換する

訳あってRMagickを試してみた。
手始めに、前にどっかで見た画像をHTMLに変換するのをやってみる。

で、こんな感じになった。

require "rubygems"
require "activesupport"
require "RMagick"

exit unless file = ARGV.shift

def hex_color(px)
  format("#%x%x%x", px.red >> 8, px.blue >> 8, px.green >> 8)
end

img = Magick::ImageList.new(file)
puts "<html><body><div style='width:#{img.columns}px'>"
img.get_pixels(0,0,img.columns, img.rows).each_slice(img.columns) do |ps|
  ps.each {|p| puts "<div style='background:#{hex_color(p)}; width:1px; height:1px; float:left;'></div>"}
end
puts "</div></body></html>"

1pxのdivに背景色を指定して元画像の横幅分並べている。
このソースをconvert.rbという名前で保存して

ruby convert.rb image_file > test.html

すると、test.htmlに画像をわざわざHTMLに変換して
書き出すという寸法さ!html開くと重いから注意してくれよ!