我正在尝试编写一个图像选择器,它将从图库中选择一个图像并将其设置为ImageView
的来源。我使用下面给出的代码执行此操作,但在我在图库中选择图像并且应用程序返回Fragment
后,我收到错误:
I/PICTURE: Path: /storage/emulated/0/DCIM/Camera/IMG_20160409_130537213.jpg
E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/DCIM/Camera/IMG_20160409_130537213.jpg: open failed: EACCES (Permission denied)
I/System.out: resolveUri failed on bad bitmap uri: /storage/emulated/0/DCIM/Camera/IMG_20160409_130537213.jpg
以下是代码:
Fragment.java
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_account, container, false);
........
........
profile_img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, SELECT_PICTURE);
//SELECT_PICTURE = 1; defined in the fragment class
}
});
//The onActivityResult method
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SELECT_PICTURE
&& resultCode == Activity.RESULT_OK) {
String path = getPathFromCameraData(data, this.getActivity());
Log.i("PICTURE", "Path: " + path);
if (path != null) {
profile_img.setImageURI(Uri.parse(path));
}
}
}
//The string used to get the file(image) location
public static String getPathFromCameraData(Intent data, Context context) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
return picturePath;
}
在清单中,我已正确声明该应用需要访问设备存储空间
<manifest>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application>
....
</application>
</manifest>
可能是什么问题?任何帮助表示赞赏。 谢谢!
答案 0 :(得分:3)
取消getPathFromCameraData()
并更改
profile_img.setImageURI(Uri.parse(path));
到
profile_img.setImageURI(data.getData());
答案 1 :(得分:2)
如果您要从图库中选择图片,则需要此权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />