Tiny Rhino script for fetching Flickr images.

Covert operations have begun here in Sunnyvale on an itty-bitty Flickr project. My project uses the Flickr API to do some things you would expect to do with Flickr… fetch images, fetch image metadata, etc.

As I’m developing, I’m finding myself hitting the Flickr servers with a ton image requests… not very courteous of me. I decided to take the highroad, and download a nice set of images, serve them locally, and point my fledgling Flickr app to localhost while developing.

I’m such a nice guy.

Sounds like a job for your favorite scripting language, right? Lots of folks I know prefer Python or Ruby for something like this… but I am, and always have been a JavaScript junkie. Plus, I’m completely unfamiliar with Py and Rb standard libraries, but well-versed in the J2SE.

RHINO to the rescue.

I think a lot of people have heard of Rhino, but I’m not sure how many know just how swell it is… Here’s a quick rundown of a tiny little Rhino script to fetch some remote images. See my earlier post for how to easily install Rhino on OS X.

First, import some Java packages needed for HTTP:


importPackage(java.io, java.net);

Next, get an array of URL strings for images you’re interested in:


var urlStrs = ["http://static.flickr.com/119/292857754_1b153997bc_m.jpg"];

Loop through the URL strings, create a java.net.URL for each, and open its java.io.InputStream:


for (var i=0; i < urlStrs.length; i++) {
    var urlStr = urlStrs[i];
    var url = new URL(urlStr);
    var r = url.openStream();

Create a java.io.FileOutputStream, and write to disk. Don’t forget to flush.


    var filename = "imgs" + urlStr.substring(urlStr.lastIndexOf("/"));
    var w = new FileOutputStream(filename);
    var b;
    while ((b = r.read()) > -1) {
        w.write(b);
    }
    w.flush();
    w.close();
    r.close();
}
print("DONE! You are a fabulous, wonderful individual.");

Rhino is fun.

This post brought to you by BlogMate.


About this entry