在Facebook Android SDK上分享照片

时间:2016-08-01 14:51:02

标签: android facebook bitmap facebook-android-sdk

我正在尝试使用Android SDK在Facebook上分享照片。

问题是我的Bitmap图片为空。这是我的代码:

public void sharePhoto(View view) {
        if (Session.getInstance().getUserFace().getBestphoto() == null) {
            Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, RESULT_LOAD_IMAGE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            Log.d("picture path", picturePath);
            BitmapFactory.Options options = new BitmapFactory.Options();
            try {
                Bitmap image = BitmapFactory.decodeFile(picturePath, options);
                uploadPhoto(image);
            } catch (OutOfMemoryError e) {
                try {
                    options = new BitmapFactory.Options();
                    options.inSampleSize = 2;
                    Bitmap image = BitmapFactory.decodeFile(picturePath, options);
                    uploadPhoto(image);
                } catch (Exception ex) {
                    Log.e("EXCEPTION", ex.toString());
                }
            }
        }
    }

    private void uploadPhoto(Bitmap image) {
        Log.d("Image", "" + image);
        SharePhoto photo = new SharePhoto.Builder()
                .setBitmap(image)
                .build();
        SharePhotoContent content = new SharePhotoContent.Builder()
                .addPhoto(photo)
                .build();
        ShareDialog.show(MainActivity.this, content);
    }

2 个答案:

答案 0 :(得分:0)

您可以尝试从InputStream获取位图。使用此,

BitmapFactory.decodeStream(resolver.openInputStream(uri), null, options);

解析器是ContentResolveruri返回data.getData();

除非您想检查任何FileNotFoundException,否则您不需要查询数据库。

答案 1 :(得分:0)

File file = new File(picturePath);
Uri imageUri = Uri.fromFile(file.getAbsoluteFile()); 
try {
    Bitmap image = BitmapFactory.decodeStream(mContext.getContentResolver().openInputStream(imageUri));
    uploadPhoto(image); 
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
  1. 您来自MediaStore的“ picturePath” 光标,它可能像这样 /storage/emulated/0/DCIM/Camera/IMG20200513xx.jpg
  2. 您可以尝试将路径更改为内容URI(文件:///storage/emulated/0/DCIM/Camera/IMG20200513xx.jpg )。
  3. 使用内容提供商的 getContentResolver()打开图像。然后将图像解码为位图。