【问题标题】:Android How to get image path of contact photo?Android 如何获取联系人照片的图片路径?
【发布时间】:2017-08-11 09:24:03
【问题描述】:

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

我低于 uri。

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

【问题讨论】:

  • 使用该 uri 上传该图像。哦,即使存在,也不需要真正的文件路径。
  • @greenapps 当我尝试使用 multipart 将图像发送到服务器时,我得到 File not found Exception。
  • 然后呢?哪个声明导致了这种情况?不必对多部分做任何事情。但只有当您尝试使用该内容方案时才会发生这种情况,就好像它是文件路径一样。

标签: android path uri photo contact


【解决方案1】:

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

首先我使用联系人 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();
    }
}

文件写入成功后,使用该文件网址上传。

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

【讨论】:

  • After getting InputStream write as a file in Internal Storage.。这是一个非常糟糕的建议。有了 InputStream 后,您可以使用它直接上传图像。 InputStream 作为 OP 现在使用的 FileInputStream 的替代品。就是这样。
  • 无需更新您的答案。事实上,用它来更新你的帖子也很糟糕,因为这不是你的主意,每个人都可以阅读我的评论。相反,我希望你承认这确实是个坏主意。
猜你喜欢
  • 1970-01-01
  • 2014-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-31
  • 2011-11-12
  • 1970-01-01
相关资源
最近更新 更多