Friday, January 11, 2013

How to create and read QR codes on a Mac

Just recently I was tasked with fnding a command line tool to create QR codes (there are a lot of web pages which offer online creation but a GUI sometimes does not cut it).

My investigations had led me into much too complex territory when I finally could reduce the issue to a very simple solution by using ZXing (a Java library for QR codes). ZXing has already grown into a mighty library to support QR coding in various manners but its documentation was a little scarce for me so the following steps should give everyone a simple recipe. (Note: All of the below was done a Mac with Java 1.6)

  • Download and unzip ZXing into a directory of your choice.
    (currently version 2.1. Because this is a development build you will find a lot of directories and files)
  • Take the files core/core.jar and javase/javase.jar and put them into a new directory (preferrably outside of the ZXing tree. Afterwards you could remove the previous ZXing directory if you wanted)
  • Go to that new directory and run the commands described below

    Create a QR code file

    java -cp ./core.jar:./javase.jar \
         com.google.zxing.client.j2se.CommandLineEncoder \
         http://ajhaupt.blogspot.com
    
    will take the URL as input and create a file out.png containing the QR code.
    Here is the image:

    There are options to change the image type, dimensions and name of the output file, other QR attributes like encoding or error correction levels are fixed and you would need to create your own class to handle that.

    Decode a QR code file

    QR code decoding is mostly done via an image capture device (camera) and a corresponding application (normally on smart phones) but this ZXing command runs on a computer and allows to find and decode a QR code in image files.
    Here is the output of the file above (easy since it simply contains the QR code) but it would also work on images containing other things (with the QR code sitting somewhere) and also on images with multiple QR codes.
    java -cp ./core.jar:./javase.jar \
         com.google.zxing.client.j2se.CommandLineRunner \
         out.png
    file:/Users/......../out.png (format: QR_CODE, type: URI):
    Raw result:
    http://ajhaupt.blogspot.com
    Parsed result:
    http://ajhaupt.blogspot.com
    Found 4 result points.
      Point 0: (68.5,230.5)
      Point 1: (68.5,68.5)
      Point 2: (230.5,68.5)
      Point 3: (203.5,203.5)
    

    Since all of this is in Java it will of course run on other platforms too.

    Neither command seems to work with more complex input like vCard but corresponding modules exist in the library, I guess the command line utilities were provided by the authors as a proof of concept, it's up to the user to extend them if necessary.

  • 1 comment:

    1. Good resource! Thank you for providing such an useful sample of how to create qr code on mac.

      ReplyDelete