Android How to get image path of contact photo?

社会主义新天地 提交于 2019-12-22 18:51:51

问题


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



来源:https://stackoverflow.com/questions/42897850/android-how-to-get-image-path-of-contact-photo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!