如何从PhotoPicker Intent获取图像大小

时间:2017-09-23 18:03:37

标签: java android android-intent

这是我的On Click Listener:

@Override
public void onClick(View view) {
  Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
  intent.setType("image/jpeg");
  intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
  startActivityForResult(Intent.createChooser(intent, "Complete action using"), PHOTO_PICKER_REQUEST_CODE);
}

这是我的OnActivityResult:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  if (requestCode == PHOTO_PICKER_REQUEST_CODE && resultCode == RESULT_OK) {
     Uri selectedImageUri = data.getData();
     File imageFile = new File(getRealPathFromURI(selectedImageUri));
     long length = imageFile.length();
     length = length / 1024;
     Log.d(TAG, "onActivityResult: ImageSize " + length +" Kb");
  }
}

ImageSize始终返回0(零)。

1 个答案:

答案 0 :(得分:0)

您可能错过了清单中的权限。您需要在AndroidManifest.xml中添加以下权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

或者,如果您要定位Android 6.0(API级别23)及以上,则需要Requesting Permissions at Run Time

请检查您的getRealPathFromURI()方法。我使用以下代码进行测试并开展工作:

public String getRealPathFromURI(Uri contentUri) {
  String res = null;
  String[] proj = { MediaStore.Images.Media.DATA};
  Cursor cursor = getContentResolver().query(contentUri, proj, "", null, "");
  if (cursor.moveToFirst()) {
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    res = cursor.getString(column_index);
  }
  cursor.close();
  return res;
}

或使用Convert content:// URI to actual path in Android 4.4

中的代码