Generating Flickr Short URLs with JavaScript

Published on

As of this past Saturday, users who click a “tweet this” link on an individual photo in Portwiture may notice a few extra characters available. By popular request, the app now takes advantage of Flickr’s URL shortening.

What’s unique about flic.kr URLs is that they are not directly tied to a database or fetch-able via the API, but derived from a photo’s unique ID using a variation of base58 compression. This is actually pretty neat, as it sidesteps the need for an additional database query, resulting in a faster experience for the end user.

The only problem is that you, the developer, have to do the work to generate the darn thing. If you need to create it on the fly using JavaScript (as Portwiture does), you may be disappointed by the relative lack of JS code snippets in the official base58 flic.kr dev discussion.

Fear not! Using their PHP example, translating this functionality to JavaScript is a straightforward process.

The only function used therein with no direct JavaScript equivalent is intval. Luckily, the amazing php.js project has us covered with a translation. Grab that function and include it in your source.

Now we simply rewrite the base_encode function, swapping out strlen for .length, [] for .charAt(), and so on.

function base_encode(num, alphabet) {
  // http://tylersticka.com/
  // Based on the Flickr PHP snippet:
  // http://www.flickr.com/groups/api/discuss/72157616713786392/
  alphabet =
    alphabet || "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
  var base_count = alphabet.length;
  var encoded = "";
  while (num >= base_count) {
    var div = num / base_count;
    var mod = num - base_count * intval(div);
    encoded = alphabet.charAt(mod) + encoded;
    num = intval(div);
  }
  if (num) encoded = alphabet.charAt(num) + encoded;
  return encoded;
}

Note that the default alphabet differs slightly from honest-to-goodness base58 encoding, omitting certain characters that are confusing in URLs (0 and O, I and l, etc.).

Assuming you’ve already fetched a Flickr photo ID, generating a short URL is now as simple as this:

var shortURL = "http://flic.kr/p/" + base_encode(4379822687);
alert(shortURL);
// Should alert 'http://flic.kr/p/7F2JGg'

That’s all there is to it. Reversing the process is a bit trickier (you need to fetch the author’s name), but this Flickr discussion should get you started.

Want a JavaScript file with intval, base_encode, base_decode and a few helper functions ready and raring to go? You’re one lucky son of a gun:

Download flickr-shorturl.js 1.0