Shortening A Url And Getting A QR Code With Bit.ly

Published: {ts '2012-09-04 00:00:00'}
Author: Steven Neiland
Site Url: http://www.neiland.net/article/shortening-a-url-and-getting-a-qr-code-with-bit-ly/

As a follow up on last weeks post about an incompatibility between Railo and Adobe when reading a remote file. Today I am going to demonstrate how I use bit.ly to generate the QR Code on my article print view.

As it turns out ColdFusion and bitly make it very easy to generate and output a QR Code. I have broken it down into four steps.

Step 1: Create A Bit.ly Account And Create A Component Named Bitly.cfc

Before we can get started we first need to create an account with bitly. Once the account is created you will get a username and api key.

With these now create a component named bitly.cfc and create the following initialization function in it. The use of the third argument will become clear later on.

Step 2: Shorten The Url

With the component setup we must now create another function in the bitly component that can take the original long url and shorten it using the bit.ly api.

Step 3: Get The QR Code Binary For The Shortened Url

When bit.ly creates a shortened url it also creates a QR Code for it automatically. All we need to do now is read it using cfhttp. The QR Code is accessed using this address pattern:

http://bit.ly/{shorturlcode}.qrcode

Plugging this into a function in our bitly component we get this. Note how the isRailo flag is used to deal with the previously discussed incompatibility between ACF and Railo.

Step 4: Output The QR Code To The Browser

Finally with the byte array of the qr code image returned we need to output it to the screen. This is done with a simple call to cfimage.

You will notice that I am doing a check to see that the qrcode bytearray is not empty (i.e. The service request succeeded). I am using toString() to convert the bytearray value into a simple string that CF can compare against an empty string.

Putting It All Together

Finally we can test our completed bitly component and output method.

Long Url: #longUrl #
Shortened Url: #shortUrl#
QR Code: