It's a trap
It's a trap

Reputation: 1353

Get profile image from facebook oAuth in mvc

I have read the following post Post 1 and followed ak7's answer to get the url of fb image, but when i browse to the url, it shows a photo with grey background and a question mark. Then i tried to follow the Second post Mike Troinfo's answer and added picture as a parameter to query string, but the info variable doesn't have any parameter corresponding to image. Kindly help me in figuring out a solution to get Users DP from facebook and store it in database

var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
WebResponse response = null;
    string pictureUrl = string.Empty;
    try
    {
        WebRequest request = WebRequest.Create(string.Format("https://graph.facebook.com/{0}/picture?type=large&redirect", loginInfo.email));
        response = request.GetResponse();
        pictureUrl = response.ResponseUri.ToString();
    }

Upvotes: 0

Views: 2980

Answers (1)

Anik Saha
Anik Saha

Reputation: 4494

Before getting picture you have get access token of an user. Then you hit that url to get picture. See this link first.

May be this link help you to get authentication token.

And last of all you have to hit url like that.

https://graph.facebook.com/me/picture?redirect&access_token=CAACEdEose0cBACwZBfdwRTNjsxu1HRxyhQ78lIKGonbKaNRidTtM9QjiwuVuD6DzXsNL1qLGkc1P3sHFnElQ287I1VUBfamvdV0pfBs8dDgbOShqRh2UuviXyv4ZAZAcEEeqlZCKb39nGuTZAjssXCKhS8NZBXun9KfWwZCV29s32K37ajnYIOBelHh3gZCaJsixwXkhPXiQ5ZA2MY2flK4sz

using this you will get a json

{
 "data": {
  "is_silhouette": true,
  "url": "https://scontent.xx.fbcdn.net/hprofile-xfa1/v/t1.0-1/s200x200/10354686_10150004552801856_220367501106153455_n.jpg?_nc_eui=ARhjdKn0xJ2BpM9I6X_JD0UDCnmaSk6REHSU6yD01EeYw9avdnIb6dqiVr74&oh=3f560f9bf95ca602bb19c2d7b8870e1a&oe=57869A50"
  }
 }

Then you save the image from that url. There are lots of technique to save image from url.

{
byte [] data = webClient.DownloadData("https://fbcdn-sphotos-h-a.akamaihd.net/hphotos-ak-xpf1/v/t34.0-12/10555140_10201501435212873_1318258071_n.jpg?oh=97ebc03895b7acee9aebbde7d6b002bf&oe=53C9ABB0&__gda__=1405685729_110e04e71d9");

  using (MemoryStream mem = new MemoryStream(data)) 
  {
   using (var yourImage = Image.FromStream(mem)) 
   { 
      // If you want it as Png
       yourImage.Save("path_to_your_file.png", ImageFormat.Png) ; 

      // If you want it as Jpeg
       yourImage.Save("path_to_your_file.jpg", ImageFormat.Jpeg) ; 
   }
 } 

}

For more details see here.

Upvotes: 1

Related Questions