开发者

Uploading pictures to Facebook using Graph API with Android SDK

I am trying to upload a photo to facebook using graph api and keep getting OutOfMemory exception. The code for the upload is this:

private void PostPhoto(SessionHandler facebook, Uri photoUri)
{
    Bundle params = new Bundle();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    String realPath = getRealPathFromURI(photoUri); 
    Bitmap bitmap = BitmapFactory.decodeFile(realPath);

    bitmap.compress(CompressFormat.JPEG, 100, bos);

    params.putByteArray("picture", bos.toByteArray());


    try
    {
        facebook.mFacebook.request("me/photos", params, "POST");            

    } catch (FileNotFoundException fileNotFoundException)
    {

    } catch (MalformedURLException malformedURLException)
    {

    } catch (IOException ioException)
    {

    }

}

The exception raises on the decodeFile function and sometimes in the facebook SDK itself when it calls this line:

return Util.openUrl(url, httpMethod, parameters);

inside the request function.

The app is getting the picture content:// Uri by the ACTION_SEND intent. getRealPathFromURI() is used to translate the content:// uri to a real sdcard path.

Any ideas开发者_StackOverflow中文版?


Try this, it works for me:

byte[] data = null;
try {
    ContentResolver cr = mainActivity.getContentResolver();
    InputStream fis = cr.openInputStream(photoUri);
    Bitmap bi = BitmapFactory.decodeStream(fis);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    data = baos.toByteArray();              
} catch (FileNotFoundException e) {
    e.printStackTrace();
}     
Bundle params = new Bundle(); 
params.putString("method", "photos.upload");          
params.putByteArray("picture", data);

This is using the Rest API, the facebook sdk has the method for calling it so just change your request line from:

facebook.mFacebook.request("me/photos", params, "POST");   

to:

facebook.mFacebook.request(params);   

and hopefully that will solve the problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜