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

时间:2016-08-23 07:15:46

标签: android firebase firebase-authentication facebook-authentication

我正在使用 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()获得的照片非常小。我需要一个更大的图像,无法找到一种方法。任何帮助将受到高度赞赏。 我已经试过了 Get larger facebook image through firebase login 但它不起作用,虽然它们很快,但我认为API不应该有所不同。

7 个答案:

答案 0 :(得分:29)

It is not possible to obtain a profile picture from Firebase that is larger than the one provided by getPhotoUrl(). However, the Facebook graph makes it pretty simple to get a user's profile picture in any size you want, as long as you have the user's Facebook ID.

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);

答案 1 :(得分:15)

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

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

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

答案 2 :(得分:3)

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

您可以使用用户facebookId将此链接存储到firebase数据库,并在应用中使用此链接。 您也可以将高度更改为参数

答案 3 :(得分:1)

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

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

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
            }
        }
    }

}

答案 4 :(得分:1)

在我已经登录后,在第二个活动中使用此代码,对我来说,在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");

答案 5 :(得分:0)

注意:从Graph API v8.0中,您每次执行的UserID请求都must provide the access token

点击图形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);
        }
    });

这就是文档所说的:

从2020年10月24日开始,所有用户都需要访问令牌 基于UID的查询。如果您查询一个UID,因此必须包含一个令牌:

  • 对Facebook登录身份验证请求使用用户访问令牌
  • 将页面访问令牌用于页面范围的请求
  • 使用App访问令牌处理服务器端请求
  • 将客户端访问令牌用于移动或Web客户端请求

我们建议您仅在无法使用时使用客户端令牌。 其他令牌类型之一。

答案 6 :(得分:0)

检查下面的答复

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}');