Android : 如何使用 FirebaseAuth 从 Facebook 获取更大的个人资料图片?

Android : How to get larger profile pic from Facebook using FirebaseAuth?

我正在使用 FirebaseAuth 通过 FB 登录用户。这是代码:

private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private CallbackManager mCallbackManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());

    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();

    mAuthListener = firebaseAuth -> {
        FirebaseUser user = firebaseAuth.getCurrentUser();
        if (user != null) {
            // User is signed in
            Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
        } else {
            // User is signed out
            Log.d(TAG, "onAuthStateChanged:signed_out");
        }

        if (user != null) {
            Log.d(TAG, "User details : " + user.getDisplayName() + user.getEmail() + "\n" + user.getPhotoUrl() + "\n"
                    + user.getUid() + "\n" + user.getToken(true) + "\n" + user.getProviderId());
        }
    };
}

问题是我使用 user.getPhotoUrl() 得到的照片非常小。我需要一个更大的图像,但找不到办法做到这一点。任何帮助将不胜感激。 我已经试过了 但它不起作用,尽管它们适用于 swift 我不认为 API 应该有所不同。

无法从 Firebase 获取比 getPhotoUrl() 提供的个人资料照片更大的个人资料照片。但是,只要您拥有用户的 Facebook ID,Facebook 图表就可以非常简单地获取任意大小的用户头像。

String facebookUserId = "";
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
ImageView profilePicture = (ImageView) findViewById(R.id.image_profile_picture);

// find the Facebook profile and get the user's id
for(UserInfo profile : user.getProviderData()) {
    // check if the provider id matches "facebook.com"    
    if(FacebookAuthProvider.PROVIDER_ID.equals(profile.getProviderId())) {
        facebookUserId = profile.getUid();
    }
}

// construct the URL to the profile picture, with a custom height
// alternatively, use '?type=small|medium|large' instead of ?height=
String photoUrl = "https://graph.facebook.com/" + facebookUserId + "/picture?height=500";

// (optional) use Picasso to download and show to image
Picasso.with(this).load(photoUrl).into(profilePicture);

如果有人正在寻找这个但使用 FirebaseAuth 的 Google 帐户。我找到了解决方法。详细图片的话URL:

https://lh4.googleusercontent.com/../.../.../.../s96-c/photo.jpg

/s96-c/ 指定图像大小(在本例中为 96x96),因此您只需将该值替换为所需的大小即可。

String url= FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl();
url = url.replace("/s96-c/","/s300-c/");

您可以分析您的照片URL,看看是否有任何其他方法可以改变它的大小。

正如我一开始所说,这仅适用于 Google 个帐户。查看@Mathias Brandt 的回答以获得自定义 Facebook 个人资料图片大小。

2020 年编辑:

感谢 Andres SK 和@alextouzel 指出这一点。照片 URL 的格式已更改,现在您可以传递 URL 参数以获得不同尺寸的图片。检查 https://developers.google.com/people/image-sizing.

photoUrl = "https://graph.facebook.com/" + facebookId+ "/picture?height=500"

您可以使用用户 facebookId 将此 link 存储到 firebase 数据库,并在应用程序中使用它。 你也可以改变高度作为参数

不适用于 Android,但适用于 iOS,但我认为它可能对其他人有帮助(我没有找到此问题的 iOS 版本)。

根据提供的答案,我创建了一个 Swift 4.0 扩展,它向 Firebase User 对象添加了一个函数 urlForProfileImageFor(imageResolution:)。您可以要求标准缩略图、高分辨率(我将其设置为 1024 像素但很容易更改)或自定义分辨率图像。享受:

extension User {

    enum LoginType {
        case anonymous
        case email
        case facebook
        case google
        case unknown
    }

    var loginType: LoginType {
        if isAnonymous { return .anonymous }
        for userInfo in providerData {
            switch userInfo.providerID {
            case FacebookAuthProviderID: return .facebook
            case GoogleAuthProviderID  : return .google
            case EmailAuthProviderID   : return .email
            default                    : break
            }
        }
        return .unknown
    }

    enum ImageResolution {
        case thumbnail
        case highres
        case custom(size: UInt)
    }

    var facebookUserId : String? {
        for userInfo in providerData {
            switch userInfo.providerID {
            case FacebookAuthProviderID: return userInfo.uid
            default                    : break
            }
        }
        return nil
    }


    func urlForProfileImageFor(imageResolution: ImageResolution) -> URL? {
        switch imageResolution {
        //for thumnail we just return the std photoUrl
        case .thumbnail         : return photoURL
        //for high res we use a hardcoded value of 1024 pixels
        case .highres           : return urlForProfileImageFor(imageResolution:.custom(size: 1024))
        //custom size is where the user specified its own value
        case .custom(let size)  :
            switch loginType {
            //for facebook we assemble the photoUrl based on the facebookUserId via the graph API
            case .facebook :
                guard let facebookUserId = facebookUserId else { return photoURL }
                return URL(string: "https://graph.facebook.com/\(facebookUserId)/picture?height=\(size)")
            //for google the trick is to replace the s96-c with our own requested size...
            case .google   :
                guard var url = photoURL?.absoluteString else { return photoURL }
                url = url.replacingOccurrences(of: "/s96-c/", with: "/s\(size)-c/")
                return URL(string:url)
            //all other providers we do not support anything special (yet) so return the standard photoURL
            default        : return photoURL
            }
        }
    }

}

两行代码。 FirebaseUser user = firebaseAuth.getCurrentUser();

String photoUrl = user.getPhotoUrl().toString();
        photoUrl = photoUrl + "?height=500";

只需在末尾附加"?height=500"

注意:来自 Graph API v8.0 你 must provide the access token 为你所做的每个 UserID 请求。

打图API:

https://graph.facebook.com/<user_id>/picture?height=1000&access_token=<any_of_above_token>

使用 Firebase:

FirebaseUser user = mAuth.getCurrentUser();
String photoUrl = user.getPhotoUrl() + "/picture?height=1000&access_token=" +
  loginResult.getAccessToken().getToken();

你从registerCallback那里得到令牌就像这样

       LoginManager.getInstance().registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            FirebaseUser user = mAuth.getCurrentUser();
            String photoUrl = user.getPhotoUrl() + "/picture?height=1000&access_token=" + loginResult.getAccessToken().getToken();
        }

        @Override
        public void onCancel() {
            Log.d("Fb on Login", "facebook:onCancel");
        }

        @Override
        public void onError(FacebookException error) {
            Log.e("Fb on Login", "facebook:onError", error);
        }
    });

文档是这么说的:

Beginning October 24, 2020, an access token will be required for all UID-based queries. If you query a UID and thus must include a token:

  • use a User access token for Facebook Login authenticated requests
  • use a Page access token for page-scoped requests
  • use an App access token for server-side requests
  • use a Client access token for mobile or web client-side requests

We recommend that you only use a Client token if you are unable to use one of the other token types.

我在第二个 Activity 中使用此代码,在已经登录后,对我来说,在 loginResult.getAccessToken().getToken(); 中获得的令牌会在一段时间后过期,所以研究我发现了这个和它为我服务

final String img = mAuthProvider.imgUsuario().toString(); // is = mAuth.getCurrentUser().getPhotoUrl().toString;
        
final String newToken = "?height=1000&access_token=" + AccessToken.getCurrentAccessToken().getToken();
        
Picasso.get().load(img + newToken).into("Image reference");

检查下面的回复

final graphResponse = await http.get(
'https://graph.facebook.com/v2.12/me?fields=name,picture.width(800).height(800),first_name,last_name,email&access_token=${fbToken}');