Get Image from Gallery with Intent

空扰寡人 提交于 2020-01-25 21:47:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!