简体   繁体   English

意图从图库中获取图像

[英]Get Image from Gallery with Intent

I want to get a image from Gallery with the share command. 我想使用share命令从图库中获取图像。

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 imageUri的值是:content:// media / external / images / media / 37

But the function "openInputStream" throws the error "java.io.FileNotFoundException". 但是函数“ openInputStream”抛出错误“ 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. 但我不知道如何将其转换为位图。

A Uri is not a File . Uri不是File new File(imageUri.toString()) is always wrong. new File(imageUri.toString())总是错误的。 imageUri.getPath() only works if the scheme of the Uri is file , and in your case, the scheme is probably content . imageUri.getPath()仅在Uri的方案为file时才起作用,并且在您的情况下,该方案可能是content

Use ContentResolver and openInputStream() to get an InputStream on the file or content identified by the Uri . 使用ContentResolveropenInputStream()Uri标识的文件或内容上获取InputStream Then, pass that stream to BitmapFactory.decodeStream() . 然后,将该流传递给BitmapFactory.decodeStream()

Also, please decode bitmaps on a background thread, so that you do not freeze your UI while this work is going on. 另外,请在后台线程上解码位图,以免在进行此工作时冻结UI。

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

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