Android: How to crop images using CameraX?

camerax image analysis
android camera preview image processing
android camerax example
android crop image
exceeded max simultaneously bound image capture use cases
camerax preview data
android camerax source code
crop image in android example

I want to take a photo and crop out a square of 25x25 dp from the center using CameraX. I have read that cropping is possible using ImageCapture but unfortunately there are almost no similar examples out there so far.

val imageCaptureConfig = ImageCaptureConfig.Builder().apply {
    setTargetAspectRatio(Rational(1, 1))
    setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY)
}.build()

val imageCapture = ImageCapture(imageCaptureConfig)
btn_take_photo.setOnClickListener {
    imageCapture.takePicture(
        object : ImageCapture.OnImageCapturedListener() {
            override fun onCaptureSuccess(image: ImageProxy?, rotationDegrees: Int) {
                super.onCaptureSuccess(image, rotationDegrees)

                // image manipulation here?
            }
        }
    )
}

You can convert the image to a Bitmap and then crop it.

Bitmap cropImage(Image image, int rotationDegree, int xOffset, int yOffset, int cropWidth, int cropHeight) {
    // 1 - Convert image to Bitmap
    ByteBuffer buffer = image.getPlanes()[0].getBuffer();
    byte[] bytes = new byte[buffer.remaining()];
    buffer.get(bytes);
    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

    // 2 - Rotate the Bitmap
    if(rotationDegree != 0) {
        Matrix rotationMatrix = new Matrix();
        rotationMatrix.postRotate(rotationDegree);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), rotationMatrix, true);
    }

    // 3 - Crop the Bitmap
    bitmap = Bitmap.createBitmap(bitmap, xOffset, yOffset, cropWidth, cropHeight);

    return bitmap;
}

Exploring the new CameraX library in Android, CameraX library is build to simplify the usage of camera features in provides additional information for a view to crop, scale, or rotate for proper display. The image analysis use-case provides a virtually accessible image� I want to take a photo and crop out a square of 25x25 dp from the center using CameraX. I have read that cropping is possible using ImageCapture but unfortunately there are almost no similar examples out there so far.

Output streams and cropping, Cropping of the full pixel array (for digital zoom and other use cases on the crop region, the dimensions of the image sensor, and the lens� Apps should include the camera-lifecycle library to use CameraX. See notes in the camera-core section for how to perform initialization of CameraX using a ProcessCameraProvider. Camera-Extensions and Camera-View Version 1.0.0 Camera-Extensions Version 1.0.0-alpha14. July 22, 2020. androidx.camera:camera-extensions:1.0.0-alpha14 is released.

You can get the planes from the image and crop them manually:

private fun cropByteArray(array : ByteArray, cropRect: Rect): ByteArray {
    val croppedArray = ByteArray(cropRect.width()*cropRect.height())
    val imageWidth = 640
    var i = 0
    array.forEachIndexed { index, byte ->
        val x = index % imageWidth
        val y = index / imageWidth

        if (cropRect.left <= x && x < cropRect.right && cropRect.top <= y && y < cropRect.bottom) {
            croppedArray[i] = byte
            i++
        }
    }
    return croppedArray
}

......

val buffer = image.planes[0].buffer
val imageByteArray = buffer.toByteArray()
val data = cropByteArray(imageByteArray, cropRect)

ImageCapture, When it comes to CameraX, there are several different use cases which have been catered Image Analysis – Used to perform analysis on images. Int // Match longest sides together -- i.e. apply center-crop transformation if� Android Studio 3.6 or above. Using the Android Studio menu, start a new project and select Empty Activity when prompted. Next, name the app "CameraX App". Make sure that the language is set to Kotlin, the minimum API level is 21 (which is the minimum required for CameraX) and that you use AndroidX artifacts. Add the Gradle dependencies

Exploring CameraX on Android: Use Cases – Joe Birch, Crop image and save result to file. Using the Code. Let's start! Create a new project in Android studio (I used version 3.2.1) or you can download� Image capture: captures and saves a photo. Use cases can be combined and active concurrently. For example, an app can let the user view the image that the camera sees using a preview use case, have an image analysis use case that determines whether the people in the photo are smiling, and include an image capture use case to take a picture once

Crop Image from Camera on Android, start picker to get image for cropping and then use the image in cropping activity CropImage.activity() .setGuidelines(CropImageView.Guidelines.ON) .start(this);� Great Starter article for CameraX Joe, Just a quick query, since we already mentioned “view_camera.bindToLifecylce(this)” in onCreate, Is it required to write CameraX.unbindAll in onDestroy?

ArthurHub/Android-Image-Cropper: Image Cropping , This article is based on a presentation from the Android Dev Summit 2019 with Image Analysis, enabling you to access camera frame data to CameraX will figure out the crop region and send a request to the camera and� Android CameraX : Use Cases. CameraX has come up with a use case-based approach to focus on the task you need to get done instead of spending time managing device-specific configurations. The three core use cases are: Preview – What you see. The Camera Feed. Image Analysis – What you do. Processing the Camera Feed. Image Capture – What

Comments
  • Do you specifically want to do this using CameraX ? If not, you might use Glide, and its Transformations for that.
  • I could also use Glide, yeah. I thought maybe there are some functions since CameraX seems pretty powerful.
  • CameraX is mostly an API to interact with the camera(s) of the device. It's more hardware-related stuffs. Image manipulation isn't really something this API was designed to achieve.
  • Ok Thank you very much Arthur! Helped a lot already. I can mark your answer if you write it down as an answer
  • Unfortunately I wouldn't be able to answer the actual question. Cropping a fixed-size square out of an image is harder than I expected with Glide. You might take a look at this article which explains how to achieve it. You might answer the question yourself afterwards.
  • When I use this function this line BitmapFactory.decodeByteArray(bytes, 0, bytes.length); returned null
  • decodeByteArray returns null if the image cannot be decoded as mentioned here: developer.android.com/reference/android/graphics/…. Can you validate that you have a proper image and that the bytes array was properly filled ?
  • buffer.toByteArray() thrown a unresolved reference.