Retrieving Google User Photo

Out of my own experience I figured out that if the thumbnailPhotoUrl has private on the URL then the photo is not public i.e. not viewable outside the domain, it could also be that the user hasn't activated their Google+ profile, which I believe makes their photo public anyway.

Best to avoid using the thumbnailPhotoUrl if the URL has a private path on it. I think it's more reliable to retrieve the photo as Web-safe base64 data using the Users.Photo API then encode it as an inline base64 CSS image.

This is the code snippet I usually use:

    import com.google.common.io.BaseEncoding;
    import com.google.api.services.admin.directory.model.User;
    import com.google.api.services.admin.directory.model.UserPhoto;

public class PhotoUtils {

    public void loadPhoto() {
            // if the user have not signed up for Google+ yet then their thumbnail is private
            String thumbnailUrl = user.getThumbnailPhotoUrl();
            String photoData = "";
            if((thumbnailUrl != null) && (thumbnailUrl.indexOf("private") > -1)) {

                    UserPhoto photo = getUserPhoto(user.getId());
                    if(photo != null) {
                        photoData = getBase64CssImage(photo.getPhotoData(), photo.getMimeType());
                    }
            }

    }

        public static String getBase64CssImage(String urlSafeBase64Data, String mimeType) {
            urlSafeBase64Data = new String(BaseEncoding.base64().encode(
                      BaseEncoding.base64Url().decode(urlSafeBase64Data)));
            return "data:" + mimeType + ";base64," + urlSafeBase64Data;
        }

         public UserPhoto getUserPhoto(String userId) throws IOException {
            UserPhoto photo = null;
            try {
                photo = this.getClient().users().photos().get(userId).execute();

            } catch(GoogleJsonResponseException e) {
                if(e.getMessage().indexOf(NOT_FOUND) == 0) {
                    log.warning("No photo is found for user: " + userId);

                } else {
                    throw e;
                }
            }
            return photo;
        }
}