Android 10
以上就很簡單,直接使用MediaStore
抓到圖片路徑,然後送給圖片剪裁就好
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val selection = "${MediaStore.Images.ImageColumns.DISPLAY_NAME} = '$pictureName'"
val orderBy = "${MediaStore.Images.ImageColumns.DATE_ADDED} DESC"
val uriQuery = contentResolver.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null,
selection,
null,
orderBy
) ?: return@registerForActivityResult
uriQuery.moveToFirst()
val pictureId =
uriQuery.getLong(uriQuery.getColumnIndex(MediaStore.Images.ImageColumns._ID))
val pictureUri = ContentUris.withAppendedId(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
pictureId
)
val contentValue = ContentValues().apply {
this.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, cropPictureName)
this.put(MediaStore.Images.ImageColumns.MIME_TYPE, "image/jpeg")
this.put(
MediaStore.Images.ImageColumns.RELATIVE_PATH,
"${Environment.DIRECTORY_PICTURES}/AndroidSystem"
)
}
val cropUri = contentResolver.insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
contentValue
)
intent.setDataAndType(pictureUri, "image/*")
intent.putExtra(MediaStore.EXTRA_OUTPUT, cropUri)
cropPictureResultLauncher.launch(intent)
return@registerForActivityResult
}