我使用ACTION_PICK意图从图库中获取图像: -
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, 112);
并且在onActivityResult()中,我按getData()
获取图片,该图片返回给我uri: - /external/images/media/6097
现在,当我通过setImageUri()
imageview方法在imageview中设置此uri时,图像正在显示,但是当我创建一个文件对象以在服务器上上传此图像时: -
File imageFile = new File(uri);
说文件不存在。 imageFile.exists()
返回false。
我不知道问题出在哪里。我在genymotion和设备上尝试了这个,但结果是一样的。 在清单中,我已经授予权限: -
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
答案 0 :(得分:2)
尝试从uri获取绝对路径,并使用绝对路径创建文件实例,而不是uri:
public String getAbsolutePath(Uri uri) {
if (Build.VERSION.SDK_INT >= 19) {
String id = "";
if (uri.getLastPathSegment().split(":").length > 1)
id = uri.getLastPathSegment().split(":")[1];
else if (uri.getLastPathSegment().split(":").length > 0)
id = uri.getLastPathSegment().split(":")[0];
if (id.length() > 0) {
final String[] imageColumns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media.ORIENTATION};
Uri tempUri = getUri();
Cursor imageCursor = getContentResolver().query(tempUri, imageColumns, MediaStore.Images.Media._ID + "=" + id, null, null);
if (imageCursor.moveToFirst()) {
return imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
} else {
return null;
}
} else {
return null;
}
} else {
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Images.Media.ORIENTATION};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}
答案 1 :(得分:0)
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == getActivity().RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImageUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
if (!TextUtils.isEmpty(picturePath)) {
Log.v(TAG, "SELECT_PICTURE... " + picturePath);
}
}
} else {
Toast.makeText(getActivity(), " File discarded...", Toast.LENGTH_LONG).show();
}
}