如何编辑联系人照片

时间:2020-05-18 15:22:44

标签: android android-studio kotlin android-contacts

我想使用Kotlin用新的位图bmp作为个人资料图片更新联系人。我找到了editing contacts的文档,但是在意图页面上找不到用于更改照片的字段。我发现所有的堆栈溢出解决方案都涉及到奇怪的更新方法,即使开发人员页面鼓励使用意图。更改联系人照片的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

首先,永远不要使用bmp,这是一个很大的文件,您不想将bmp照片放入任何数据库中。

因此,现在要将图片插入到特定的原始联系人,并假设您手边有一些标准图片文件(jpeg / png),您可以执行以下操作:

val rawContactPhotoUri = Uri.withAppendedPath(
    ContentUris.withAppendedId(RawContacts.CONTENT_URI, yourRawContactId), // note that this must be a RAW-contact-id, not a contact-id
    RawContacts.DisplayPhoto.CONTENT_DIRECTORY
) // this is the url the represents a RawContact picture

try {
    val bytes = yourPictureFile.toByteArray() // get a byte array from your pic
    val fd = context.contentResolver.openAssetFileDescriptor(rawContactPhotoUri, "rw")
    val os = fd?.createOutputStream()
    os?.write(bytes)
    os?.close()
    fd?.close()
} catch (e: IOException) {
    // Handle the error
}