我正在使用以下代码,但未获取图像的路径?我已经在许多StackOverflow问题和答案中看到了代码,并且已经在Android API 19和API 22上进行了测试。请帮助我。
private void selectImage() {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, PICK_FILE_REQUEST_CODE);
}
以下代码用于onActivityResult。
@Override
public void onActivityResult(final int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode== Activity.RESULT_OK){
}
//Picking file from memory
if(requestCode == PICK_FILE_REQUEST_CODE && resultCode== Activity.RESULT_OK){
Uri uri = data.getData();
File imageFile = new File(getPathFromURI(uri));
final double imageSize = (imageFile.length()+0.0)/(1024+0.0);
try {
//Compressing
Bitmap bitmap = SiliCompressor.with(getActivity()).getCompressBitmap(getPathFromURI(uri));
onPhotoSelectedListener.getImageBitmap(bitmap, imageSize);
} catch (Exception e) {
/*
Glide.with(getContext()).asBitmap().load(uri).into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
onPhotoSelectedListener.getImageBitmap(resource, imageSize);
}
});
*/
}
getDialog().dismiss();
}
}
/*----------------------------------------------------------------------*/
public String getPathFromURI(Uri contentUri) {
String res = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}