iT邦幫忙

2021 iThome 鐵人賽

DAY 17
0
Mobile Development

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

110/17 - Android 6圖片剪裁

沒想到會因為圖片剪裁中斷,以前都偷懶使用uCrop,這次想說練習內建的剪裁,結果有夠麻煩

Android 6如果要圖片剪裁,路徑開頭是file://,所以要用Uri.fromFile()uri轉成真實路徑

val intent = Intent("com.android.camera.action.CROP").apply {
    this.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION)
    this.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    this.putExtra("crop", true)
    this.putExtra("return-data", false)
    this.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString())
    this.putExtra("scale", true)
}

val cropPictureName = "005_crop_${System.currentTimeMillis()}.jpg"

val phoneFile = File(
    Environment.getExternalStoragePublicDirectory("${Environment.DIRECTORY_PICTURES}/AndroidSystem"),
    pictureName
)
val cropPhoneFile = File(
    Environment.getExternalStoragePublicDirectory("${Environment.DIRECTORY_PICTURES}/AndroidSystem"),
    cropPictureName
)


if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {

    val pictureUri = Uri.fromFile(phoneFile)
    val cropUri = Uri.fromFile(cropPhoneFile)

    intent.setDataAndType(pictureUri, "image/*")
    intent.putExtra(MediaStore.EXTRA_OUTPUT, cropUri)
    Log.d("maho", "intent: $intent")
    cropPictureResultLauncher.launch(intent)
    return@registerForActivityResult
}

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

尚未有邦友留言

立即登入留言