Reputation: 1123
I am using Jetpack compose for my UI, Activity Result Contracts and ArthutHub Android Image Cropper Library to crop images in my App. Everything works fine as expected with the following code:
val (result, launcher) = setUpContentPhotoCropImageIntent()//this activity result
//contracts in launched on a button press
result.value?.let {
//code here to save the image and show it in the UI, upload to cloud storage etc.
}
@Composable
fun setUpContentPhotoCropImageIntent(): Pair<MutableState<Uri?>,
ManagedActivityResultLauncher<Any?, Uri?>> {
val cropActivityResultContract = object : ActivityResultContract<Any?, Uri?>() {
override fun createIntent(context: Context, input: Any?): Intent {
CropImage.isExplicitCameraPermissionRequired(context)
CropImage.getPickImageChooserIntent(context)
return CropImage
.activity()
.setActivityTitle("Choose Photo")
.setCropMenuCropButtonTitle("Select")
.setAllowRotation(true)
.setGuidelines(CropImageView.Guidelines.ON_TOUCH)
.setCropShape(CropImageView.CropShape.RECTANGLE)
.setAllowFlipping(true)
.setOutputCompressQuality(100)
.setFixAspectRatio(true)
.setMaxCropResultSize(
2000,
2000
)
.getIntent(context)
}
override fun parseResult(resultCode: Int, intent: Intent?): Uri? {
return CropImage.getActivityResult(intent)?.uri
}
}
val result = remember { mutableStateOf<Uri?>(null) }
val launcher = rememberLauncherForActivityResult(cropActivityResultContract) {
result.value = it
}
return Pair(result, launcher)
}
So with this approach, the library takes care of not only cropping images but also capturing them via camera/gallery. I would like to pass a Bitmap image myself(by getting images using the built-in Android APIs to Take Picture and get Gallery Image) and use this library for just cropping, so that I can have 2 dedicated buttons for the user to either capture photo or choose from Gallery.
I have the image now, I want this library to just crop it for me, How do i Pass an Image into it?
Upvotes: 5
Views: 1550
Reputation: 3978
Try to use the latest library https://github.com/CanHub/Android-Image-Cropper
and them you can pass the image like this:
class MainActivity {
private val cropImage = registerForActivityResult(CropImageContract()) { result ->
if (result.isSuccessful) {
// use the returned uri
val uriContent = result.uriContent
val uriFilePath = result.getUriFilePath(context) // optional usage
} else {
// an error occurred
val exception = result.error
}
}
private fun startCrop() {
// start cropping activity for pre-acquired image saved on the device and customize settings
cropImage.launch(
options(uri = imageUri) {
setGuidelines(Guidelines.ON)
setOutputCompressFormat(CompressFormat.PNG)
}
)
}
}
Upvotes: 1