Adding Imgur Support to Tweetbot for Mac

The leading Twitter client for iOS just made its OS X debut on Thursday, and it has a very interesting feature. In the application’s preferences window, you can set the services that are used for URL shortening, image hosting, reading later, and so on. In addition to the usual suspects, you can choose “custom” as an option for image uploads.

Federico Viticci included a couple of PHP scripts in his review that interface with the Tweetbot uploader and save the image to either Rackspace Files or your own server.

Well, I didn’t want to be left out of the fun, so I wrote one for Imgur, the supremely famous image host that grew out of Reddit’s habit of using up other image hosts’ low per-image bandwidth allotments.

class TweetbotImgurEndpoint {
    private $api_key;
    private $api_url = "";
    private $file_temp_location;
    private $file_name;
    function __construct($api_key, $file_temp_location, $file_name) {
        $this->api_key = $api_key;
        $this->file_temp_location = $file_temp_location;
        $this->file_name = $file_name;
    private function upload() {
        $image_info = getimagesize($this->file_temp_location);
        if ($image_info !== false && in_array($image_info['mime'], array("image/png", "image/jpeg", "image/pjpeg", "image/gif"))) {
            $fh = fopen($this->file_temp_location, "rb");
            $file_contents = fread($fh, filesize($this->file_temp_location));
            $data = array("image" => base64_encode($file_contents));
            $options = array('http' => array(
                'method'  => 'POST',
                'header' => 'Authorization: Client-ID ' . $this->api_key,
                'content' => http_build_query($data)
            $context  = stream_context_create($options);
            $result = file_get_contents($this->api_url, false, $context);
            $result = json_decode($result);
            $url = $result->data->link;
            echo json_encode(array('url' => $url));
        } else {
            echo "Could not upload image: invalid format.";
if ($_POST) {
    $imgur_api_key = 'YOUR_IMGUR_CLIENT_ID'; //replace with the "client ID" Imgur gives you
    $imgur = new TweetbotImgurEndpoint($imgur_api_key, $_FILES['media']['tmp_name'], $_FILES['media']['name']);

Just upload that to your web server, replace YOUR_IMGUR_CLIENT_ID with a client ID obtained from here. (You want to select the “anonymous usage without user authorization” option.)

Edit, 2013/10/25: Imgur has since changed their API. This post has been updated to reflect the changes. If you’re looking for the original code, for version 2 of the API, it can be found in this GitHub Gist.

  • Ikk200

    Which one? It gives me “Client ID:” or “Client Secret:”?