【发布时间】:2016-10-03 13:06:55
【问题描述】:
我正在使用下面的代码从设备库中选择一个图像文件:
首先我将这段代码称为:
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(i, "Select Picture"), RESULT_LOAD_IMAGE);
这是我的onActivityResult 方法:
@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) {
photoPath = getPath(data.getData());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileInputStream fis;
try {
fis = new FileInputStream(new File(photoPath));
byte[] buf = new byte[1024];
int n;
while (-1 != (n = fis.read(buf))) {
baos.write(buf, 0, n);
}
img.setImageBitmap(BitmapFactory.decodeFile(photoPath));
} catch (Exception e) {
e.printStackTrace();
}
}
}
这是一个检索图像路径的辅助方法:
private String getPath(Uri uri) {
String[] data = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(getApplicationContext(), uri, data, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
我的问题是应用程序很奇怪。在我的 6.0 模拟器中,有时它可以工作,有时不能。在其他设备(Android 5.1.1)中,FileNotFound Exception 会在此行抛出
fis = new FileInputStream(new File(photoPath));
所有必需的权限都很好。你们知道这里发生了什么吗?或者你有什么更好的建议来从画廊中挑选图像?
【问题讨论】:
标签: android image action gallery photo-gallery