Android : Getting a Bitmap from a url connection (graph.facebook.com) that redirects to another url

前端 未结 2 1952
情书的邮戳
情书的邮戳 2021-01-15 15:59

I have done everything to get a url where i can get the profile pic of a facebook user.

The only problem left now is to get that image into a bitmap object.

相关标签:
2条回答
  • 2021-01-15 16:30

    Update : The method given by Sahil Mittal works absolutely fine and i would definitely ask you guys to use his method.

    As for the method I used in the meantime you can read this answer.

    I dont know whether the method given by Sahil Mittal works or not.

    I havent tried that but i used another code segment which seems to work for me.

    But i will get back whether it works or not as soon as i try it.

    Bitmap getUserBitmap(String username){
    
    
            HttpGet httpRequest = null;
    
            Bitmap userbmp = null;
    
            try {
                URL url = new URL("http://graph.facebook.com/" + username + "/picture?type=small");
    
                httpRequest = new HttpGet(url.toURI());
    
                HttpClient httpclient = new DefaultHttpClient();
    
                HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
    
                HttpEntity entity = response.getEntity();
    
                BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
    
                InputStream instream = bufHttpEntity.getContent();
    
                userbmp = BitmapFactory.decodeStream(instream);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
            userbmp = getRoundedShape(userbmp); // function call to make the image round
            return (userbmp);
        }
    
    0 讨论(0)
  • 2021-01-15 16:43

    You are right in saying that http://graph.facebook.com redirects the connection first (as we can see in the url) to https://fbcdn-profile-a.akamaihd.net/, but-

    auto redirection works automatically when original and redirected protocols are same.

    So, if you try to load images from https instead of http : "https://graph.facebook.com/USER_ID/picture"; since image's url is "https://fbcdn-profile-a.akamaihd.net/....", BitmapFactory.decodeStream shall work again to get you the bitmap.

    Here's the code-

    URL imgUrl = new URL("https://graph.facebook.com/{user-id}/picture?type=large");
    InputStream in = (InputStream) imgUrl.getContent();
    Bitmap  bitmap = BitmapFactory.decodeStream(in);
    

    Hope that helps. Good luck.

    0 讨论(0)
提交回复
热议问题