a digital scan of a 35mm film image of a processing sketch running on an LCD
Skip to Content

Upload to Flickr from Processing

About The PImage Uploader
I’ve attached a quick Processing sketch that uploads PImages from a camera directly to Flickr each time you click the mouse.

The actually upload process is pretty simple — it just involves posting a bunch of bytes over HTTP to a specific URL. The hard part is getting Flickr to believe that you are who you say you are so that it will accept the images you upload.

That’s where this code is meant to help. In order to upload images to a Flickr account, your app will need write permission. In order to get write permission, you’ll need to go through the authentication process.

Basically, the first time your app wants to upload it will open up a URL on the Flickr website prompting you to log in and “allow” the app to do what it wants to do. You may be familiar with this procedure if you’ve had to authenticate third party apps that tie into Flickr (such as iPhoto or a desktop flickr uploader). In the case of the attached code, Processing opens the authentication link for you, and then gives you 15 seconds to approve the app on Flickr’s website before continuing on its way.

After this, it stores the authentication data in a text file (called token.txt) local to the Processing sketch, so that you won’t have to go through the online authentication process each time you run the app. I’ve encapsulated this process into a single function called authenticate() to make things as simple as possible. If the token is lost or becomes corrupted, the app will automatically try to fetch a new one the next time it runs. (Note that you should not distribute any sketches with your own generated token file!)

The code makes use of a Flickr library for Java called flickrj. Since flickrj is a generic Java library and isn’t designed specifically for Processing, its use is not quite as intuitive as you’re accustomed to. For one, the steps to use the library with your sketch are a bit different. Instead of putting files in your ~/Documents/Processing/libraries folder, you’ll need to download the .jar file from the flickrj website and drag and drop it onto your sketch window. This creates a folder called “code” inside your sketch folder with a copy of the .jar file inside for your sketch to reference as needed.

If you prefer, you can create the folder and copy the .jar file manually. You’ll end up with the same setup as if you dragged and dropped the file. Also note that you’ll never see anything appear in the “import” menu list since flickrj wasn’t built with Processing in mind. The flickrj jar is included in the zipped uploader code below to make your life easier.


The API / Library Conundrum
The amount of code and number steps involved in getting the necessary authorization is kind of ridiculous. It’s easy to imagine a range of places to improve upon the library.

Flickrj is a pretty direct mirror to the official Flickr API, and that’s how most API libraries are designed. It seems to be designed for experienced Java programmers working on large-scale projects instead of the quick and dirty sketches typical to Processing work. It’s tough to find exactly the right balance between a library that makes sense relative to the official API, and one that adds new features or code and leverages the paradigms of a particular programming language or framework.

For example, a Processing-specific library might incorporate a threaded image downloader that could return arrays of PImages from a given query. It could also wrap up the authorizations into a few lines of code as outlined in this post. These Processing-esque abstractions on top of Flickr’s own API abstractions add a lot of code and maintenance liabilities to our hypothetical library — but it would certainly open things up for beginner coders.

My Processing to-do list is pretty long, but I’ll add a new Flickr library filed under “maybe someday”.


The Code
The core of the sketch is shown below, but note that it will be easiest to download flickr_uploader.zip for testing since it includes the flickrj library. The code looks a bit lengthy and convoluted, but it mostly consists of helper functions to take care of the authentication process and image compression to make the upload process as simple as possible — and the helper functions should be reusable without modification, so all you really need to worry about is creating the Flickr object, calling the authentication function, and then uploading to your heart’s desire.

  1. // Simple sketch to demonstrate uploading directly from a Processing sketch to Flickr.
  2. // Uses a camera as a data source, uploads a frame every time you click the mouse.
  3.  
  4. import processing.video.*;
  5. import javax.imageio.*;
  6. import java.awt.image.*;
  7. import com.aetrion.flickr.*;
  8.  
  9. // Fill in your own apiKey and secretKey values.
  10. String apiKey = "********************************";
  11. String secretKey = "****************";
  12.                    
  13. Flickr flickr;
  14. Uploader uploader;
  15. Auth auth;
  16. String frob = "";
  17. String token = "";
  18.  
  19. Capture cam;
  20.  
  21. void setup() {
  22.   size(320, 240);
  23.  
  24.   // Set up the camera.
  25.   cam = new Capture(this, 320, 240);  
  26.  
  27.   // Set up Flickr.
  28.   flickr = new Flickr(apiKey, secretKey, (new Flickr(apiKey)).getTransport());
  29.  
  30.   // Authentication is the hard part.
  31.   // If you’re authenticating for the first time, this will open up
  32.   // a web browser with Flickr’s authentication web page and ask you to
  33.   // give the app permission. You’ll have 15 seconds to do this before the Processing app
  34.   // gives up waiting fr you.
  35.  
  36.   // After the initial authentication, your info will be saved locally in a text file,
  37.   // so you shouldn’t have to go through the authentication song and dance more than once
  38.   authenticate();
  39.  
  40.   // Create an uploader
  41.   uploader = flickr.getUploader();
  42. }
  43.  
  44. void draw() {
  45.   if (cam.available()) {
  46.     cam.read();
  47.     image(cam, 0, 0);
  48.     text("Click to upload to Flickr", 10, height - 13);
  49.   }
  50. }
  51.  
  52. void mousePressed() {
  53.   // Upload the current camera frame.
  54.   println("Uploading");
  55.  
  56.   // First compress it as a jpeg.
  57.   byte[] compressedImage = compressImage(cam);
  58.  
  59.   // Set some meta data.
  60.   UploadMetaData uploadMetaData = new UploadMetaData();
  61.   uploadMetaData.setTitle("Frame " + frameCount + " Uploaded from Processing");
  62.   uploadMetaData.setDescription("To find out how, go to http://frontiernerds.com/upload-to-flickr-from-processing");  
  63.   uploadMetaData.setPublicFlag(true);
  64.  
  65.   // Finally, upload/
  66.   try {
  67.     uploader.upload(compressedImage, uploadMetaData);
  68.   }
  69.   catch (Exception e) {
  70.     println("Upload failed");
  71.   }
  72.  
  73.   println("Finished uploading");  
  74. }
  75.  
  76. // Attempts to authenticate. Note this approach is bad form,
  77. // it uses side effects, etc.
  78. void authenticate() {
  79.   // Do we already have a token?
  80.   if (fileExists("token.txt")) {
  81.     token = loadToken();    
  82.     println("Using saved token " + token);
  83.     authenticateWithToken(token);
  84.   }
  85.   else {
  86.    println("No saved token. Opening browser for authentication");    
  87.    getAuthentication();
  88.   }
  89. }
  90.  
  91. // FLICKR AUTHENTICATION HELPER FUNCTIONS
  92. // Attempts to authneticate with a given token
  93. void authenticateWithToken(String _token) {
  94.   AuthInterface authInterface = flickr.getAuthInterface();  
  95.  
  96.   // make sure the token is legit
  97.   try {
  98.     authInterface.checkToken(_token);
  99.   }
  100.   catch (Exception e) {
  101.     println("Token is bad, getting a new one");
  102.     getAuthentication();
  103.     return;
  104.   }
  105.  
  106.   auth = new Auth();
  107.  
  108.   RequestContext requestContext = RequestContext.getRequestContext();
  109.   requestContext.setSharedSecret(secretKey);    
  110.   requestContext.setAuth(auth);
  111.  
  112.   auth.setToken(_token);
  113.   auth.setPermission(Permission.WRITE);
  114.   flickr.setAuth(auth);
  115.   println("Authentication success");
  116. }
  117.  
  118.  
  119. // Goes online to get user authentication from Flickr.
  120. void getAuthentication() {
  121.   AuthInterface authInterface = flickr.getAuthInterface();
  122.  
  123.   try {
  124.     frob = authInterface.getFrob();
  125.   }
  126.   catch (Exception e) {
  127.     e.printStackTrace();
  128.   }
  129.  
  130.   try {
  131.     URL authURL = authInterface.buildAuthenticationUrl(Permission.WRITE, frob);
  132.    
  133.     // open the authentication URL in a browser
  134.     open(authURL.toExternalForm());    
  135.   }
  136.   catch (Exception e) {
  137.     e.printStackTrace();
  138.   }
  139.  
  140.   println("You have 15 seconds to approve the app!");  
  141.   int startedWaiting = millis();
  142.   int waitDuration = 15 * 1000; // wait 10 seconds  
  143.   while ((millis() - startedWaiting) < waitDuration) {
  144.     // just wait
  145.   }
  146.   println("Done waiting");
  147.  
  148.   try {
  149.     auth = authInterface.getToken(frob);
  150.     println("Authentication success");
  151.     // This token can be used until the user revokes it.
  152.     token = auth.getToken();
  153.     // save it for future use
  154.     saveToken(token);
  155.   }
  156.   catch (Exception e) {
  157.     e.printStackTrace();
  158.   }
  159.  
  160.   // complete authentication
  161.   authenticateWithToken(token);
  162. }
  163.  
  164. // Writes the token to a file so we don’t have
  165. // to re-authenticate every time we run the app
  166. void saveToken(String _token) {
  167.   String[] toWrite = { _token };
  168.   saveStrings("token.txt", toWrite);  
  169. }
  170.  
  171. boolean fileExists(String filename) {
  172.   File file = new File(sketchPath(filename));
  173.   return file.exists();
  174. }
  175.  
  176. // Load the token string from a file
  177. String loadToken() {
  178.   String[] toRead = loadStrings("token.txt");
  179.   return toRead[0];
  180. }
  181.  
  182. // IMAGE COMPRESSION HELPER FUNCTION
  183.  
  184. // Takes a PImage and compresses it into a JPEG byte stream
  185. // Adapted from Dan Shiffman’s UDP Sender code
  186. byte[] compressImage(PImage img) {
  187.   // We need a buffered image to do the JPG encoding
  188.   BufferedImage bimg = new BufferedImage( img.width,img.height, BufferedImage.TYPE_INT_RGB );
  189.  
  190.   img.loadPixels();
  191.   bimg.setRGB(0, 0, img.width, img.height, img.pixels, 0, img.width);
  192.  
  193.   // Need these output streams to get image as bytes for UDP communication
  194.   ByteArrayOutputStream baStream        = new ByteArrayOutputStream();
  195.   BufferedOutputStream bos              = new BufferedOutputStream(baStream);
  196.  
  197.   // Turn the BufferedImage into a JPG and put it in the BufferedOutputStream
  198.   // Requires try/catch
  199.   try {
  200.     ImageIO.write(bimg, "jpg", bos);
  201.   }
  202.   catch (IOException e) {
  203.     e.printStackTrace();
  204.   }
  205.  
  206.   // Get the byte array, which we will send out via UDP!
  207.   return baStream.toByteArray();
  208. }

December 17 2010 at 3 PM

thank you for your source~

January 23 2013 at 12 PM