Search code examples
androidbitmapandroid-cameraandroid-camera2

Convert View Rect coordinates to bitmap area


I have camera screen with rectangle(simple view) inside, to make photo the user need to place object inside the rectangle, after taking picture the app need to cut image and show only the area inside rectangle.

  • From camera2 api i receives the image and converting him to bitmap.
  • I have the Rectangle coordinates on screen.

The problem is that the bitmap width/height for example 5472/7296, and the Rect coordinates related to device screen left-114 top-764 width-852 height-609, how i can convert it to area on bitmap to cut the bitmap in Rect's area.

I am cutting the bitmap using

Bitmap createBitmap(Bitmap source, int x, int y, int width, int height)

I have tried to calculate with percentage but it not ideal(about 5% inaccuracy).


Solution

  • So the solution was to scale the bitmap to screens size.

    Bitmap bitmap = BitmapUtil.scaleBitmap(bitmap, screenWidth, screenHeight);
    

    Then crop by the Rect cordinates

    Bitmap cropBitmap = Bitmap.createBitmap(bitmap, rect.left, rect.top, rect.width(), rect.height());