有很多方法可以使用第三方或默認應用程序編輯圖像。 Intent.SetAction(Intent.ACTION_EDIT)startActivity不返回任何內容。所以這裏是獲取編輯圖像路徑的解決方案。
val editIntent = Intent(Intent.ACTION_EDIT)
editIntent.setDataAndType(textImage.uri, "image/*")
editIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
//ContextCompat.startActivity(context, Intent.createChooser(editIntent, null), null)
(context as Activity).startActivityForResult(Intent.createChooser(editIntent, null), IMAGE_EDIT_REQUEST_CODE)
如果最小Api級別超過19,那麼onActivityResult數據集將返回FileProvider內容。
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
when(requestCode) {
IMAGE_EDIT_REQUEST_CODE -> {
try {
val filePath = getRealPathFromUri(this, data!!.data)
etText?.setUpdatedImageResult(filePath)
} catch (ex: Exception) {
}
}
else -> return
}
}
}
內容不給編輯的圖像路徑,然後使用內容提供商獲取新保存的圖像路徑。
fun getRealPathFromUri(context: Context, uri: Uri): String {
var filePath = ""
if (uri.host.contains("com.android.providers.media")) {
// Image pick from recent
val wholeID = DocumentsContract.getDocumentId(uri)
// Split at colon, use second item in the array
val id = wholeID.split(":")[1]
val column = arrayOf(MediaStore.Images.Media.DATA)
// where id is equal to
val sel = MediaStore.Images.Media._ID + "=?"
val cursor = context.contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,column, sel, arrayOf(id), null)
val columnIndex = cursor.getColumnIndex(column[0])
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex)
}
cursor.close()
return filePath
} else {
// image pick from gallery
return getRealPathFromUriBelowAPI11(context, uri)
}
}