Sample code for 30+ languages & platforms
Java

Facebook Download all Photos to Local Files

See more Facebook Examples

Demonstrates how to download all of one's Facebook photos to a local filesystem directory. This sample code keeps a local cache to avoid re-downloading the same photos twice. The program can be run again after a time, and it will download only photos that haven't yet been downloaded.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.Cache;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.FileAccess;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.OAuth2;
import com.chilkatsoft.chilkat2.Rest;
import com.chilkatsoft.chilkat2.StringArray;
import com.chilkatsoft.chilkat2.StringBuilder;

public class ChilkatExample {

    public static void main(String[] args) {
        // This example requires the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        // This example will use a local disk cache to avoid re-fetching the same
        // photo id after it's been fetched once.
        Cache fbCache = new Cache();
        // The cache will use 1 level of 256 sub-directories.
        fbCache.setLevel(1);
        // Use a directory path that makes sense on your operating system..
        fbCache.addRoot("C:/fbCache");

        // This example assumes a previously obtained an access token
        OAuth2 oauth2 = new OAuth2();
        oauth2.setAccessToken("FACEBOOK-ACCESS-TOKEN");

        Rest rest = new Rest();

        // Connect to Facebook.
        String responseJson;
        try {
            rest.connect("graph.facebook.com", 443, true, true);

            // Provide the authentication credentials (i.e. the access key)
            rest.setAuthOAuth2(oauth2);

            // There are two choices:
            // We can choose to download the photos the person is tagged in or has uploaded
            // by setting type to "tagged" or "uploaded".
            rest.addQueryParam("type", "uploaded");

            // To download all photos, we begin with an outer loop that iterates over
            // the list of photo nodes in pages.  Each page returned contains a list of
            // photo node ids.  Each photo node id must be retrieved to get the download URL(s)
            // of the actual image.

            // I don't know the max limit for the number of records that can be downloaded at once.
            rest.addQueryParam("limit", "100");

            // Get the 1st page of photos ids.
            // See https://developers.facebook.com/docs/graph-api/reference/user/photos/ for more information.
            responseJson = rest.fullRequestNoBody("GET", "/v2.7/me/photos");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        JsonObject photoJson = new JsonObject();
        StringArray saPhotoUrls = new StringArray();
        StringBuilder sbPhotoIdPath = new StringBuilder();

        JsonObject json = new JsonObject();
        json.setEmitCompact(false);
        json.load(responseJson);

        int i = 0;
        String photoId = "";
        String imageUrl = "";

        // Get the "after" cursor.
        String afterCursor = json.stringOf("paging.cursors.after");
        while (json.getLastMethodSuccess()) {
            System.out.println("-------------------");
            System.out.println("afterCursor = " + afterCursor);

            // For each photo id in this page...
            i = 0;
            int numItems = json.sizeOfArray("data");
            while (i < numItems) {
                json.setI(i);
                photoId = json.stringOf("data[i].id");
                System.out.println("photoId = " + photoId);

                // We need to fetch the JSON for this photo.  Check to see if it's in the local disk cache,
                // and if not, then get it from Facebook.
                String photoJsonStr = null;
                try {
                    photoJsonStr = fbCache.fetchText(photoId);
                } catch (ChilkatException e) {
                    // It's not locally available, so get it from Facebook..
                    sbPhotoIdPath.clear();
                    sbPhotoIdPath.append("/v2.7/");
                    sbPhotoIdPath.append(photoId);

                    rest.clearAllQueryParams();
                    rest.addQueryParam("fields", "id,album,images");

                    System.out.println("Fetching photo node from Facebook...");

                    // This REST request will continue using the existing connection.
                    // If the connection was closed, it will automatically reconnect to send the request.
                    try {
                        photoJsonStr = rest.fullRequestNoBody("GET", sbPhotoIdPath.getAsString());
                    } catch (ChilkatException e2) {
                        System.out.println(e2.getLastErrorText());
                        return;
                    }

                    // Add the photo JSON to the local cache.
                    fbCache.saveTextNoExpire(photoId, "", photoJsonStr);
                }

                // Parse the photo JSON and add the main photo download URL to saPhotoUrls
                // There may be multiple URLs in the images array, but the 1st one is the largest and main photo URL.
                // The others are smaller sizes of the same photo.
                photoJson.load(photoJsonStr);
                imageUrl = photoJson.stringOf("images[0].source");
                if (imageUrl != null) {
                    // Actually, we'll add a small JSON document that contains both the image ID and the URL.
                    JsonObject imgUrlJson = new JsonObject();
                    imgUrlJson.appendString("id", photoId);
                    imgUrlJson.appendString("url", imageUrl);
                    saPhotoUrls.append(imgUrlJson.emit());
                    System.out.println("imageUrl = " + imageUrl);
                }

                i = i + 1;
            }

            // Prepare for getting the next page of photos ids.
            // We can continue using the same REST object.
            // If already connected, we'll continue using the existing connection.
            // Otherwise, a new connection will automatically be made if needed.
            rest.clearAllQueryParams();
            rest.addQueryParam("type", "uploaded");
            rest.addQueryParam("limit", "20");
            rest.addQueryParam("after", afterCursor);

            // Get the next page of photo ids.
            try {
                responseJson = rest.fullRequestNoBody("GET", "/v2.7/me/photos");
            } catch (ChilkatException e) {
                System.out.println(e.getLastErrorText());
                return;
            }

            json.load(responseJson);
            afterCursor = json.stringOf("paging.cursors.after");
        }

        System.out.println("No more pages of photos.");

        // Now iterate over the photo URLs and download each to a file.
        // We can use Chilkat HTTP.  No Facebook authorization (access token) is required to download
        // the photo once the URL is known.
        Http http = new Http();

        // We'll cache the image data so that if run again, we don't re-download the same image again.
        int numUrls = saPhotoUrls.getCount();
        i = 0;
        JsonObject urlJson = new JsonObject();

        FileAccess fac = new FileAccess();

        while (i < numUrls) {
            urlJson.load(saPhotoUrls.getString(i));
            photoId = urlJson.stringOf("id");
            imageUrl = urlJson.stringOf("url");

            // Check the local cache for the image data.
            // Only download and save if not already cached.
ERROR: Invalid type for Chilkat2 Java: pbytes
ERROR: Method not in Chilkat2 Java: Cache.FetchFromCache
            imageBytes = fbCache.ERROR();
            if (!fbCache.getLastMethodSuccess()) {
                //  This photo needs to be downloaded.

                StringBuilder sbImageUrl = new StringBuilder();
                sbImageUrl.append(imageUrl);

                // Let's form a filename..
                String extension = ".jpg";
                if (sbImageUrl.contains(".gif", false)) {
                    extension = ".gif";
                }

                if (sbImageUrl.contains(".png", false)) {
                    extension = ".png";
                }

                if (sbImageUrl.contains(".tiff", false)) {
                    extension = ".tiff";
                }

                if (sbImageUrl.contains(".bmp", false)) {
                    extension = ".bmp";
                }

                StringBuilder sbLocalFilePath = new StringBuilder();
                sbLocalFilePath.append("C:/Photos/facebook/uploaded/");
                sbLocalFilePath.append(photoId);
                sbLocalFilePath.append(extension);

ERROR: Invalid type for Chilkat2 Java: pbytes
ERROR: Method not in Chilkat2 Java: Http.QuickGet
                imageBytes = http.ERROR();
                if (!http.getLastMethodSuccess()) {
                    System.out.println(http.getLastErrorText());
                    return;
                }

                // We've downloaded the photo image bytes into memory.
                // Save it to the cache AND save it to the output file.
ERROR: Method not in Chilkat2 Java: Cache.SaveToCacheNoExpire
                fbCache.ERROR();
ERROR: Method not in Chilkat2 Java: FileAccess.WriteEntireFile
                fac.ERROR();

                System.out.println("Downloaded to " + sbLocalFilePath.getAsString());
            }

            i = i + 1;
        }

        System.out.println("Finished downloading all Facebook photos!");
    }
}