我需要将联系人图像上传到服务器,但无法获取真实路径。请任何人帮助我。
我正在低于 uri。
URI:content://com.android.contacts/display_photo/2,
最佳答案
首先从Contact获取InputStream。将Inpustream写入文件并保存为图像文件。最后将该图像路径上传到服务器,成功后只需删除该图像文件即可。请参阅下面的代码。
首先,我使用联系人 ID 从联系人获取 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" />
另一种无需将图像文件保存在内部存储中的方法,您可以使用 Retrofit 中的 TypeFile 类将 inputStream 作为 FileInputStream 上传。有关更多信息,请参阅链接 TypeFile in Retrofit for upload file as InputStream
关于Android 如何获取联系人照片的图像路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42897850/