ImageUtil { public static Rect computeCropRectFromAspectRatio(Size sourceSize, Rational aspectRatio) { if (!isAspectRatioValid(aspectRatio)) { Log.w(TAG, "Invalid view ratio."); return null; } int sourceWidth = sourceSize.getWidth(); int sourceHeight = sourceSize.getHeight(); float srcRatio = sourceWidth / (float) sourceHeight; int cropLeft = 0; int cropTop = 0; int outputWidth = sourceWidth; int outputHeight = sourceHeight; int numerator = aspectRatio.getNumerator(); int denominator = aspectRatio.getDenominator(); if (aspectRatio.floatValue() > srcRatio) { outputHeight = Math.round((sourceWidth / (float) numerator) * denominator); cropTop = (sourceHeight - outputHeight) / 2; } else { outputWidth = Math.round((sourceHeight / (float) denominator) * numerator); cropLeft = (sourceWidth - outputWidth) / 2; } return new Rect(cropLeft, cropTop, cropLeft + outputWidth, cropTop + outputHeight); } private  ImageUtil(); static byte[] imageToJpegByteArray(ImageProxy image); static byte[] cropByteArray(byte[] data, Rect cropRect); static boolean isAspectRatioValid(Rational aspectRatio); static boolean isAspectRatioValid(Size sourceSize, Rational aspectRatio); static Rect computeCropRectFromAspectRatio(Size sourceSize, Rational aspectRatio); static Rational rotate(
            Rational rational, @RotationValue int rotation);  }
@Test public void canComputeRectFromAspectRatio() { Rational targetAspectRatio = new Rational(2, 1); Rect resultRect = ImageUtil.computeCropRectFromAspectRatio(new Size(WIDTH, HEIGHT), targetAspectRatio); assertThat(new Rational(resultRect.width(), resultRect.height())).isEqualTo( targetAspectRatio); assertThat(new Point(resultRect.centerX(), resultRect.centerY())).isEqualTo( new Point(WIDTH / 2, HEIGHT / 2)); if (targetAspectRatio.floatValue() >= new Rational(WIDTH, HEIGHT).floatValue()) { assertEquals(WIDTH, resultRect.width()); } else { assertEquals(HEIGHT, resultRect.height()); } }