Ruby/PureImage + Rails

Ruby/PureImageを使って、Railsで動的に画像を出力してみる。

アクション

require 'pureimage'

class ImageController < ApplicationController
  def index
    out = StringIO.new
    create_image(out)

    @headers.update(
      'Content-Type'              => 'image/png',
      'Content-Disposition'       => 'inline',
      'Content-Transfer-Encoding' => 'binary'
    )

    render :text => out.string
  end

  private
  def create_image(out)
    image = PureImage::Image.new(280, 170, 0xffffff, true)
    image.draw_rect(0, 0, 279, 169, 0x000000)
    image.draw_hline(10, 22, 260, 0x000000, 255)
    image.draw_hline(10, 23, 260, 0x000000, 128)
    image.draw_hline(10, 24, 260, 0x000000,  64)
    image.draw_hline(10, 25, 260, 0x000000,  32)
    image.draw_hline(10, 26, 260, 0x000000,  16)
    image.draw_rect(20, 40, 100, 100, 0x808080)
    image.draw_rect(30, 50, 100, 100, 0x000000, 64)
    image.draw_rect(10, 60, 100, 100, 0x000000, 32)
    image.draw_line(45, 75, 95, 125, 0xff0000, 64)
    image.draw_line(45, 125, 95, 75, 0x0000ff, 64)
    image.fill_rect(160, 40, 100, 100, 0xff0000, 64)
    image.fill_rect(150, 50, 100, 100, 0x00ff00, 64)
    image.fill_rect(170, 60, 100, 100, 0x0000ff, 64)

    png = PureImage::PNGIO.new
    png.save(image, out)
  end
end

所感

  • StringIOの使い方が微妙。適切なクラスがあるような…
  • renderの使い方が微妙。適切なメソッドがあるような…
    • send_fileはファイルのパスしか引数に取れないのかなぁ?