2017-03-20 101 views
2

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

我越来越低于uri。

URI:内容://com.android.contacts/display_photo/2,

+0

那么使用该URI来上传该图像。 Yoh即使存在,也不需要真正的文件路径。 – greenapps

+0

@greenapps当即时尝试发送图像到服务器使用多部分即时获取文件未找到异常。 – Sach

+0

而且?哪个陈述导致了这一点?无需对多部分进行任何操作。但是只有当您尝试像使用文件路径一样使用该内容方案时才会发生。 – greenapps

回答

2

从Contact.Write的Inpustream文件中的第一获取InputStream和保存为图像文件。最后,成功后将图像路径上传到服务器,只需删除该图像文件即可。见下面的代码。

首先,我使用联系人ID从Contact获取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" /> 

的另一种方式,你可以上传的inputStream为使用TypeFile类改造的FileInputStream。欲了解更多信息,请参阅链接TypeFile in Retrofit for upload file as InputStream

+0

'将InputStream写入内部存储器中的文件后'。这是一个非常糟糕的建议。一旦你有了InputStream,你可以直接使用它来上传图片。一个InputStream,用于替换OP现在使用的FileInputStream。就这样。 – greenapps

+0

感谢@greenapps,现在我更新我的答案 –

+1

无需更新您的答案。事实上,更新你的文章也是不好的,因为这不是你的想法,每个人都可以阅读我的评论。相反,我希望你承认这确实是一个坏主意。 – greenapps

相关问题