2017-03-20 104 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

相關問題