繁体   English   中英

意图从图库中获取图像

[英]Get Image from Gallery with Intent

我想使用share命令从图库中获取图像。

我当前的代码是:

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");
    }

imageUri的值是:content:// media / external / images / media / 37

但是函数“ openInputStream”抛出错误“ java.io.FileNotFoundException”。

通过以下功能,我可以获得图像的真实路径。

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();
        }
    }
}

但我不知道如何将其转换为位图。

Uri不是File new File(imageUri.toString())总是错误的。 imageUri.getPath()仅在Uri的方案为file时才起作用,并且在您的情况下,该方案可能是content

使用ContentResolveropenInputStream()Uri标识的文件或内容上获取InputStream 然后,将该流传递给BitmapFactory.decodeStream()

另外,请在后台线程上解码位图,以免在进行此工作时冻结UI。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM