Retrieving Google User Photo

六眼飞鱼酱① 提交于 2019-12-06 03:42:49

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;
        }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!