Android 如何获取联系人照片的图像路径?

标签 android path uri photo contacts

我需要将联系人图像上传到服务器,但无法获取真实路径。请任何人帮助我。

我正在低于 uri。

URI:content://com.android.contacts/display_photo/2,

最佳答案

首先从Contact获取InputStream。将Inpustream写入文件并保存为图像文件。最后将该图像路径上传到服务器,成功后只需删除该图像文件即可。请参阅下面的代码。

首先,我使用联系人 ID 从联系人获取 InputStream。

getContactInputStream("58");//58 is my contact id.

 public void getContactInputStream(String contactId)
{
    Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(contactId));
    InputStream stream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(), uri);
    saveContactImage(stream);
}

获取InputStream后将其作为文件写入内部存储中。

public void saveContactImage(InputStream inputStream) {
    try {
        File file = new File(Environment.getExternalStorageDirectory().getPath(), "contactImage.png");
        OutputStream output = new FileOutputStream(file);
        try {
            try {
                byte[] buffer = new byte[4 * 1024]; // or other buffer size
                int read;

                while ((read = inputStream.read(buffer)) != -1) {
                    output.write(buffer, 0, read);
                }
                output.flush();
            } finally {
                output.close();
            }
        } catch (Exception e) {
            e.printStackTrace(); // handle exception, define IOException and others
        }
        Log.d(TAG," Contact Image Path ===>"+file.getAbsolutePath());
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

成功写入文件后,使用该文件 URL 进行上传。

file.getAbsolutePath()// Output : /storage/emulated/0/contactImage.png

上述任务需要以下权限:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />

另一种无需将图像文件保存在内部存储中的方法,您可以使用 Retrofit 中的 TypeFile 类将 inputStream 作为 FileInputStream 上传。有关更多信息,请参阅链接 TypeFile in Retrofit for upload file as InputStream

关于Android 如何获取联系人照片的图像路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42897850/

相关文章:

android - 从android应用程序上传视频到http服务器

android - Firebase 云消息传递是否需要服务器?

linux - 如何在 Unix/Linux 中获取进程的路径

eclipse - Intellij IDEA模块默认 "user.dir"

android - react 原生 : Android soft keyboard push the View up

c# - 如何获取类库的当前目录?

c# - 如何创建使用 GenericUriParserOptions.DontCompressPath 解析的 Uri 实例

java - 注册和使用自定义 java.net.URL 协议(protocol)

ruby - 如何避免双重编码 URI

java - 无法从firebase数据库android、回收器 View 中检索数据