LoginSignup
28
31

More than 5 years have passed since last update.

Ruby ( Rails ) で 文字を追加した QR コードを簡単に生成する方法

Last updated at Posted at 2015-01-18

Ruby で QR コードを生成

gem をインストール

$ gem install rmagick
$ gem install rqrcode_png

サンプルコード

QRコードに「hoge」という情報を埋め込み、生成された QR コードの下部の中心に「id: hoge」を表示して、PNGファイルで保存します。

    require 'fileutils'
    require 'RMagick'
    require 'rqrcode'
    require 'rqrcode_png'
    require 'chunky_png'

    text = 'hoge'
    qrimage = "tmp.png"
    width = 150
    height = 150
    qr = RQRCode::QRCode.new(text, :size => 10, :level => :h)
    qr.to_img.resize(width, height).save(qrimage) # tmp.png のファイル名で一旦 png ファイルを保存

    image = Magick::Image.read(qrimage).first
    # x は 150 の半分の 75 とし、y は 150 だと下に表示がかぶってしまうので、2px 上げておく
    draw.annotate(image, 0, 0, width / 2, height - 2, "id: #{text}") do
      self.fill = '#000000'
      self.align = Magick::CenterAlign
      self.stroke = 'transparent'
      self.pointsize = 8
      self.text_antialias = true
      self.kerning = 1
    end

    image.write("qr.png")
    FileUtils.rm(qrimage, {:force => true}) # tmp ファイルを削除

Rails で QR コードを生成

gem をインストール

下記を Gemfile に追加して、bundle install

Gemfile
gem 'rmagick', :require => 'RMagick'
gem 'rqrcode_png'

サンプルコード

QRコードに「hoge」という情報を埋め込み、生成された QR コードの下部の中心に「id: hoge」を表示する

ファイルには保存せず、data_url に変換して View で表示する

Controller

    require 'chunky_png/rmagick' # Magick::Image、ChunkyPNG::Image 間の変換に使用

    text = 'hoge'
    width = 150
    height = 150

    qr = RQRCode::QRCode.new(text, :size => 10, :level => :h)
    # ChunkyPNG::Image を Magick::Image に変換
    image = ChunkyPNG::RMagick.export(qr.to_img.resize(width, height))

    draw = Magick::Draw.new
    draw.annotate(image, 0, 0, width / 2, height - 2, "id: #{shop.id}") do
      self.fill = '#000000'
      self.align = Magick::LeftAlign
      self.stroke = 'transparent'
      self.pointsize = 8
      self.text_antialias = true
      self.kerning = 1
    end

    # Magick::Image を ChunkyPNG::Image に変換して、DetaUrl に
    @qrpng = ChunkyPNG::RMagick.import(image).to_data_url

View ( haml )

%img { src: "#{qrpng}" }

参考URL

http://dharry.hatenablog.com/entry/2013/09/08/164335
http://qiita.com/ryosy383/items/c753103c93fa177e4466

28
31
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
28
31