Monday, June 18, 2007

Produce PNG barcode images from a Ruby on Rails application using RMagick and Gbarcode


This is a Ruby on Rails controller that produces PNG barcode images using RMagick (http://rmagick.rubyforge.org/) and Gbarcode (http://gbarcode.rubyforge.org/). You will need to install RMagick and Gbarcode.

On Mac OS X, you can use the Locomotive RMagick bundle (http://locomotive.raaum.org/bundles/index.html) if you install the gbarcode gem into it first, for instance:

% export GEM_HOME=/Applications/Locomotive2/Bundles/rmagickRailsMar2007_i386.locobundle/framework/lib/ruby/gems/1.8/
% gem install gbarcode

To use it, save this code as barcode_controller.rb in the apps/controllers directory of your Rails application. Generate the barcodes using a URL like this:

http://localhost:3000/barcode/send_barcode?string=A-string-to-encode


This example uses the BARCODE_128 encoding; you can use different barcode encodings by adjusting the code.


require 'RMagick'
require 'gbarcode'

class BarcodeController < ApplicationController

def send_barcode
@image_data = get_barcode_image
send_data(@image_data, :type => 'image/png',
:disposition => 'inline')
end

def get_barcode_image
string_to_encode = params[:string]
if string_to_encode.nil?
string_to_encode = "No string specified"
end
eps_barcode = get_barcode_eps(string_to_encode)
return convert_eps_to_png(eps_barcode)
end

def get_barcode_eps(string_to_encode)
bc = Gbarcode.barcode_create(string_to_encode)
Gbarcode.barcode_encode(bc, Gbarcode::BARCODE_128)
read_pipe, write_pipe = IO.pipe
Gbarcode.barcode_print(bc, write_pipe, Gbarcode::BARCODE_OUT_EPS)
write_pipe.close()
eps_barcode = read_pipe.read()
read_pipe.close()
return eps_barcode
end

def convert_eps_to_png(eps_image)
im = Magick::Image::read_inline(Base64.b64encode(eps_image)).first
im.format = "PNG"
read_pipe, write_pipe = IO.pipe
im.write(write_pipe)
write_pipe.close()
png_image= read_pipe.read()
read_pipe.close()
return png_image
end

end

No comments :