Readable QR codes in Terminal

January 22, 2014 | Comments Off

Recently I needed to generate some QR codes securely. So the usual solution of going to one of the multitude of online QR code generators wasn’t an option. I found the rQRCode ruby gem looked straight forward and required no external dependencies. It even has a handy to_s function that renders it in rough ASCII, even though it’s not readable by QR code readers. The to_s method lets your override true/false values with your own strings.

The next step was to render it on the console without having to get too fancy. My first thought was the high-ASCII ANSI block codes, but the way my terminal was configured that wasn’t working. Then I realized I was overthinking it. I just need to change the background color of a ” ” (space) character (technically two space characters made something that more resembled a square pixel). I found the colorize gem and it also had straight forward documentation and examples.

There was one final, minor problem. My terminal has a black background, so I added some white padding around the QR code to make it legible by my QR code reader. This was fairly trivial to do in code although probably faster to change the terminal background color. Here’s the code I ended up with:

# Pablo Averbuj - 2014-01-21 - Public Domain
# Gist available here: https://gist.github.com/pabloav/8553319
require 'rqrcode' # install this gem
require 'colorize' # install this gem
b = "  ".colorize(:background => :black); w =  "  ".colorize(:background => :white) # these should each contain two spaces
url = "http://www.google.com/"
# you may have to increase the :size parameter (and the w * 51 correspondingly) depending of the content you're encoding
qr = RQRCode::QRCode.new(url, :size => 8); puts w * 51; qr.to_s(:true => b, :false => w).split("\n").each{|l| puts w + l + w } ; puts w * 51

The final result looks something like this:

qrcode

 

Update: 2016/08/03

I revisited this code and made it autosize the QR code automatically. The code is slightly longer but easier. All you need to do now is change the value of URL. Gist URL is the same: https://gist.github.com/pabloav/8553319

 


No Comments yet

Sorry, the comment form is closed at this time.