问题
I want to get a image from Gallery with the share command.
My current code is:
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
Log.d("Test","Simple SEND");
Uri imageUri = (Uri)intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (imageUri != null) {
InputStream iStream = getContentResolver().openInputStream(imageUri);
}
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
Log.d("Test", "Multiple SEND");
}
The value of the imageUri is: content://media/external/images/media/37
But the function "openInputStream" throws the error "java.io.FileNotFoundException".
With the following function i get the real path of the image.
public static String getRealPathFromUri(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
But i don't know how to convert it to a bitmap.
回答1:
A Uri is not a File. new File(imageUri.toString()) is always wrong. imageUri.getPath() only works if the scheme of the Uri is file, and in your case, the scheme is probably content.
Use ContentResolver and openInputStream() to get an InputStream on the file or content identified by the Uri. Then, pass that stream to BitmapFactory.decodeStream().
Also, please decode bitmaps on a background thread, so that you do not freeze your UI while this work is going on.
来源:https://stackoverflow.com/questions/43916090/get-image-from-gallery-with-intent