iT邦幫忙

2021 iThome 鐵人賽

DAY 19
0
Mobile Development

重新瞭解Android硬體控制系列 第 14

110/19 - Android 10以上圖片剪裁

  • 分享至 

  • xImage
  •  

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
}

上一篇
110/18 - Android 7到Android 9圖片剪裁
系列文
重新瞭解Android硬體控制14
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言