Android How to get image path of contact photo?

2019-05-23 21:10发布

问题:

I need to upload contact image to server but not able to get real path. Please anyone help me.

I'm getting below uri.

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

回答1:

first get InputStream from Contact.Write the Inpustream in file and save as Image File. Finally upload that image path to server after success simply delete that Image File. See below code.

First I get InputStream from Contact by using Contact Id.

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);
}

After getting InputStream write as a file in Internal Storage.

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();
    }
}

After successfully File Write then use that File Url to upload.

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

Following Permission are required for above Task :

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

Another way without saving Image file in internal storage you can upload inputStream as FileInputStream using TypeFile class in Retrofit. For more info see the Link TypeFile in Retrofit for upload file as InputStream