title: Cropping a rectangle out of Camera2 Image
body: <p>I have a YUV_420_888 image I got from the camera. I want to crop a rectangle out of grayscale of this image to feed to an image processing algorithm. This is what I have so far:</p>
  
  <pre><code>public static byte[] YUV_420_888toCroppedY(Image image, Rect cropRect) {
      byte[] yData;
  
      ByteBuffer yBuffer = image.getPlanes()[0].getBuffer();
  
      int ySize = yBuffer.remaining();
  
      yData = new byte[ySize];
  
      yBuffer.get(yData, 0, ySize);
  
      if (cropRect != null) {
  
          int cropArea = (cropRect.right - cropRect.left) * (cropRect.bottom - cropRect.top);
  
          byte[] croppedY = new byte[cropArea];
  
          int cropIndex = 0;
  
          // from the top of the rectangle, to the bottom, sequentially add rows to the output array, croppedY
          for (int y = cropRect.top; y &lt; cropRect.top + cropRect.height(); y++) {
  
              // (2x+W) * y + x
              int rowStart = (2*cropRect.left + cropRect.width()) * y + cropRect.left;
  
              // (2x+W) * y + x + W
              int rowEnd = (2*cropRect.left + cropRect.width()) * y + cropRect.left + cropRect.width();
  
              for (int x = rowStart;  x &lt; rowEnd; x++) {
                  croppedY[cropIndex] = yData[x];
                  cropIndex++;
              }
          }
  
          return croppedY;
      }
  
      return yData;
  }
  </code></pre>
  
  <p>This function runs without error but the image I get out of it is garbage - it looks something like this:</p>
  
  <p><a href="https://i.stack.imgur.com/xDQHP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xDQHP.png" alt="enter image description here"></a></p>
  
  <p>I'm not sure how to solve this problem or what I'm doing wrong. </p>