android - 获取图片路径

标签 android android-intent mime-types mime

我创建了一个 mime 类型的 Activity ,如下图所示。

<activity android:name=".xxxx"                        
            android:launchMode="singleTop"
            android:excludeFromRecents="true"
            android:configChanges="orientation|screenSize|keyboardHidden"
            android:theme="@style/AppTheme">                        
            <intent-filter>
                <action android:name="android.intent.action.SEND" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:host="xxxx.xxxx.net"></data>
                 <data android:mimeType="image/*" />            
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.CHOOSER" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:host="xxxx.xxxx.net"/>
                 <data android:mimeType="image/*" />
            </intent-filter>
            </activity>  

现在,当用户单击照片并转到图库并共享我的应用程序时,当他单击它时,我能够启动上述 Activity ...现在我的问题是如何获取该图像的路径?

最佳答案

这将为您提供 .xxxx Activity

中 Uri 实例的路径
Uri uri = (Uri) getIntent().getExtras().get(Intent.EXTRA_STREAM);

然后,如果您需要在 ImageView 中显示图像,请使用:

imageView.setImageURI(uri);

可选代码:

如果您还需要图像在设备上的绝对路径(当我使用 TwitPic API 将图像上传到 Twitter 时,我发现这是一个必要的约束),那么下面的代码将为您提供File 实例中设备上图像的绝对路径。由于 OP 中的这一点不清楚,我认为一些额外的代码不会有什么坏处。 ;-)

// PASS THE URI INSTANCE FROM THE CODE ABOVE IN THE CONSTRUCTOR
File file = new File(getRealPathFromURI(uri));

和方法getRealPathFromURI(Uri uri):

public String getRealPathFromURI(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null); 
    cursor.moveToFirst(); 
    int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
    return cursor.getString(idx); 
}

并使用 File 文件实例设置图像:

imageView.setImageUri(Uri.fromFile(file));

关于android - 获取图片路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16012671/

相关文章:

android - NDK : how include *. Android Studio 中的 so 文件

java - 获取 fragment 中的区域设置

email - 您能确定一封电子邮件是否仅从电子邮件标题中包含附件吗

php - file->getMimeType() 始终使用 Zend Framework 返回 application/octet-stream

java - 如何在打开应用程序时读取文本文件?

android - 如何在按钮上方显示文本?

java - 我的应用程序在启动之前崩溃了。这是一个简单的应用程序,我在其中使用 Intent 来调用前一个类中的另一个类

f4v 的 HTML5 MIME 类型

java - pubnub api回调方法错误不会覆盖其父类(super class)中的方法

android - 当我尝试从EditText捕获时,Android App崩溃