Generate a Barcode in Ruby with Barby and a small extension

For an inventory application I am currently developing, I needed a way to generate a barcode for products that were input into the system.
Fortunately Tore Darell has developed a super simple barcode library named Barby
Barby generated the barcodes perfectly. I choose to use the RMagick outputter, as I already had that set up on my system.
Simple Example using the RMagick Outputter
require 'rubygems' require 'barby' require 'barby/outputter/rmagick_outputter'barcode = Barby::Code128B.new('Barcode Code Here') File.open('code128B.png', 'w'){|f| f.write barcode.to_png }
Produces

See the Barby documentation for the different barcodes that are currently supported. The above example uses 128 with type B. (I don’t really understand all the different types of barcodes yet).
Extension
The above image is fine, but I needed to also output the code that was input underneath the barcode. The reason for this is so a human can recognise the codes without getting the barcode scanner out.
So I wrote this very quick extension to the Rmagic Outputter. It basically uses Rmagic to extend the canvas by 10 px in height and outputs the code at the bottom
Here is the extension with example usage at the bottom:
require 'rubygems' require 'barby' require 'barby/outputter/rmagick_outputter'module Barby class CustomRmagickOutputter < RmagickOutputter register :to_image_with_data def to_image_with_data #Make canvas bigger canvas = Magick::ImageList.new canvas.new_image(full_width , full_height + 10) canvas << to_image canvas = canvas.flatten_images #Make the text text = Magick::Draw.new text.font_family = 'helvetica' text.pointsize = 14 text.gravity = Magick::SouthGravity text.annotate(canvas , 0,0,0,0, barcode.data) canvas end end endbarcode = Barby::Code128B.new('Barcode Code Here') barcode.to_image_with_data.write('barcode_2.png')
This outputs:

As you can see the code is on the bottom which is what I needed. I hope this has helped someone. I would love to hear your comments.
You might also have noticed I have removed all the spam comments and am now using Disqus
Hamza
Comments