Tag Facebook Photos Using Graph API

0
SHARES

In my previous posts, we saw how to upload a photo from local disk or from an image url. It is also very easy to tag photos using facebook api. In order to tag a particular photo what we need to know is the left and top margin of tagging square and the user id of tagged user. The margin is calculated in percentages. The 3 inputs are passed to facebook graph api to tag the photo.

Tag Facebook Photos Using API

Now the majority of code is taken from previous post, Upload Photos to Facebook Directly from URL. There an image is uploaded from a url and the id of photo is returned by facebook. This id is then used as a parameter to tag that photo.

In order to tag a photo, our app needs user_photos and friends_photos permission from user. We will then use /[photo id]/tags connection from facebook graph api. Here is the php code to upload an image from a url and then tag the currently logged in user on the image.

if (isset($_POST["source"])) {
    try {
        $access_token = $facebook->getAccessToken();
        $graph_url = "https://graph.facebook.com/me/photos?"
                . "url=" . urlencode($_POST["source"])
                . "&message=" . urlencode($_POST['message'])
                . "&method=POST"
                . "&access_token=" . $access_token;
        $response = file_get_contents($graph_url);
        $json = json_decode($response);
        $argstag = array('to' => $user);
        $argstag['x'] = 40;
        $argstag['y'] = 40;
        $datatag = $facebook->api('/' . $json->id . '/tags', 'post', $argstag);
    } catch (FacebookApiException $e) {
        error_log('Could not post image to Facebook.');
    }
}

If instead of $user, we can specify the id of any user’s friends to tag the photo. Since both x and y values are 40. The tagging will be done 40% from left and 40% from top of the photo.

Tags:

About Joby Joseph

Author of jobyj.in. I do a lot of research on web, APIs and social networks. Codes are mainly tried on PHP, jQuery, MySQL. Please support this blog by your facebook likes, twitter follow and RSS Subscribtion. Read more Google+