Android如何获取联系人照片的图像路径? [英] Android How to get image path of contact photo?

查看:125
本文介绍了Android如何获取联系人照片的图像路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我低于uri.

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

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

推荐答案

首先从Contact中获取InputStream.将Inpustream写入文件并另存为图像文件.最后,成功删除该映像文件后,只需将该映像路径上载到服务器即可.参见下面的代码.

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.

首先,我使用Contact ID从Contact中获取InputStream.

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

在将InputStream写入文件后,将其存储在内部存储器中.

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" />

另一种无需将图像文件保存在内部存储器中的方法,可以使用Retrofit中的TypeFile类将inputStream作为FileInputStream上载.有关更多信息,请参阅链接翻新中的TypeFile,以便将文件上传为InputStream

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

这篇关于Android如何获取联系人照片的图像路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆