'Image cropper in Jetpack Compose?

I have searched everywhere but didn't got a single documentation about cropping images in Jetpack Compose
How to crop Image in Jetpack Compose?



Solution 1:[1]

You can actually just use those older Android libraries no problem.

I used this one: https://github.com/CanHub/Android-Image-Cropper

Project build.gradle:

allprojects {
    repositories {
        google()
        mavenCentral()
        maven(url = "https://jitpack.io")
    }
}

App build.gradle:

implementation("com.github.CanHub:Android-Image-Cropper:4.0.0")

Usage (CropImageContract is provided by the above):

@Composable
fun ImageSelectorAndCropper() {
    var imageUri by remember {
        mutableStateOf<Uri?>(null)
    }
    val context = LocalContext.current
    val bitmap =  remember {
        mutableStateOf<Bitmap?>(null)
    }

    val imageCropLauncher = rememberLauncherForActivityResult(CropImageContract()) { result ->
        if (result.isSuccessful) {
            // use the cropped image
            imageUri = result.uriContent
        } else {
            // an error occurred cropping
            val exception = result.error
        }
    }

    val imagePickerLauncher = rememberLauncherForActivityResult(contract = ActivityResultContracts.GetContent()) { uri: Uri? ->
        val cropOptions = CropImageContractOptions(uri, CropImageOptions())
        imageCropLauncher.launch(cropOptions)
    }

    if (imageUri != null) {
        if (Build.VERSION.SDK_INT < 28) {
            bitmap.value = MediaStore.Images.Media.getBitmap(context.contentResolver, imageUri)
        } else {
            val source = ImageDecoder.createSource(context.contentResolver, imageUri!!)
            bitmap.value = ImageDecoder.decodeBitmap(source)
        }
        Button(onClick = { imagePickerLauncher.launch("image/*") }) {
            Text("Pick image to crop")
        }
    }
}

Edit:

I also had to add this to the manifest so that the CropActivity picks up a theme

<activity android:name="com.canhub.cropper.CropImageActivity"
    android:theme="@style/Base.Theme.AppCompat"/>

Solution 2:[2]

Try this simple crop!

        Image(
            painter = painterResource(id = R.drawable.blue_bg),
            contentDescription = stringResource(R.string.background_image),
            contentScale = ContentScale.Crop,
            modifier = modifier
                .fillMaxWidth()
                .height(120.dp)
        )

It crops perfectly as per Height (this sample), as long as the height/width is < the Image size on the specific device.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 CryptoCode