Search code examples
androidimagecameraandroid-camera2

Android crop camera image


I'm building a camera app similar to barcode scanner shown in picture. I need to use both Camera and android.hardware.camera2 API to support android API >= 19.

The main idea is to have camera preview on the whole screen, but save only part that isn't darkened(or take picture of area that isn't darkened). I've already done some research and figured out that it's impossible to take only part of the picture through Camera and android.hardware.camera2 APIs(but I'm not 100% sure). So I think I need to make some manipulations over the byte array(compressed into JPEG) which I receive as a result of camera capture.

I tried to use BitmapRegionDecoder in this way:

BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(bytes, 0, bytes.length, false);
Bitmap bitmap = decoder.decodeRegion(new Rect(500, 500, 1500, 1500), null);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);

Where bytes is JPEG compressed result of camera capture. But this approach changes the orientation of the image and doesn't crop region defined by Rect(actually crops another part of the image)

I would appreciate any suggestions and hints on how to achieve desired behavior.

enter image description here


Solution

  • It has been a while, but people still interested in this question. That's why I'm sharing how I resolved this problem.

    • I save full image taken from a camera as .jpg.
    • Then I get rotation angle from .jpg file. The problem of cropping different region was because each image has rotation angle which I was able to get from ExifInterface
    • Scale crop region(light rectangle on camera) to saved image dimensions.
    • Rotate crop region for an angle which has been got previously.