Home > python > Upload an image to imgur.com from Python

Upload an image to imgur.com from Python

If you are familiar with reddit, you must have noticed that most images are hosted on imgur. I would like to upload several images from my computer and I want to collect their URLs on imgur. Let’s see how to do that.

Imgur has an API, this is what we’ll use. Anonymous upload is fine for my needs. For this you need to register and you get an API key. Under the examples there is a very simple Python code. When you execute it, pycurl prints the server’s XML response to the standard output. How to store that in a variable? From that XML we want to extract some data.

Here is an extended version of the uploader script:

#!/usr/bin/env python

import pycurl
import cStringIO
import untangle    # XML parser

def upload_from_computer(image):
    response = cStringIO.StringIO()   # XML response is stored here
    
    c = pycurl.Curl()
    
    values = [
              ("key", your_api_key),
              ("image", (c.FORM_FILE, image))]
    # OR:     ("image", "http://example.com/example.jpg")]
    # OR:     ("image", "YOUR_BASE64_ENCODED_IMAGE_DATA")]
    
    c.setopt(c.URL, "http://api.imgur.com/2/upload.xml")
    c.setopt(c.HTTPPOST, values)
    c.setopt(c.WRITEFUNCTION, response.write)   # put the server's output in here
    c.perform()
    c.close()
    
    return response.getvalue()

def process(xml):
    o = untangle.parse(xml)
    url = o.upload.links.original.cdata
    delete_page = o.upload.links.delete_page.cdata
    
    print 'url:        ', url
    print 'delete page:', delete_page

#############################################################################

if __name__ == "__main__":
    img = '/tmp/something.jpg'
    xml = upload_from_computer(img)
    process(xml)

The tip for storing the XML output in a variable is from here. Untangle is a lightweight XML parser; more info here.

About these ads
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 90 other followers

%d bloggers like this: