その他
    ホーム技術発信DoRuby【Rails】barbyでバーコードを作成してPNGで表示する【バーコード】

    【Rails】barbyでバーコードを作成してPNGで表示する【バーコード】

    この記事はアピリッツの技術ブログ「DoRuby」から移行した記事です。情報が古い可能性がありますのでご注意ください。

    「barby」を利用すると数字をバーコードにできたり、英数字をQRコードにして表示できるようになります。

    今回はでデータURIスキームで画像表示する方法を紹介します。

    この方法を使えば画像データを保存しなくて済みます。

     Githubとwikiのリンク

    Github

    https://github.com/toretore/barby

    wiki

    https://github.com/toretore/barby/wiki

     1.Gemfileに「 gem ‘barby’」と記述してbundle install

    	$ vim Gemfile
    	=================
    	gem ‘barby’
    	=================
    	$ bundle install
    	

     2.バーコード作成用のclassを作成

    	class Barcode
    	  require 'barby'
    	  require 'barby/barcode/ean_13'
    	  require 'barby/barcode/ean_8'
    	  require 'barby/outputter/png_outputter'
    	
    	  def initialize(number, type = :ean_13)
    	    @number = number.to_s
    	    @type = type
    	  end
    	
    	  # PNG形式でデータURIスキームを生成
    	  def to_png_image
    	    'data:image/png;base64, ' + Base64.encode64(Barby::PngOutputter.new(barcode(@type, @number)).to_png)
    	  end
    	
    	  private
    	
    	  def barcode(type, data)
    	    case type
    	    when :ean_13 # 13桁の場合
    	      Barby::EAN13.new(data)
    	    when :ean_8 # 8桁の場合
    	      Barby::EAN8.new(data)
    	    end
    	  end
    	end
    	

     3.controllerでの記述

    	def index
    	   @barcode = Barcode.new(491234567890)
    	end
    	

     4.viewでの記述

    	<%= image_tag @barcode.to_png_image %>
    	

    他にもQRコードの作成やテーブルタグでの出力方法等もあったりします。詳しくは公式wikiをご確認ください。