我们可以在this answer 中了解解决此问题的一般方法。短引用:
我的解决方案是首先将预览选择矩形缩放到本机相机图片大小。然后,既然我知道原生分辨率的哪个区域包含我想要的内容,我可以执行类似的操作,然后将原生分辨率上的矩形缩放为每个 Camera.Parameters.setPictureSize 实际捕获的较小图片。
现在,到实际代码。执行缩放的最简单方法是使用Matrix。它有 Matrix#setRectToRect(android.graphics.RectF, android.graphics.RectF, android.graphics.Matrix.ScaleToFit) 方法,我们可以这样使用:
// Here previewRect is a rectangle which holds the camera's preview size,
// pictureRect and nativeResRect hold the camera's picture size and its
// native resolution, respectively.
RectF previewRect = new RectF(0, 0, 480, 800),
pictureRect = new RectF(0, 0, 1080, 1920),
nativeResRect = new RectF(0, 0, 1952, 2592),
resultRect = new RectF(0, 0, 480, 800);
final Matrix scaleMatrix = new Matrix();
// create a matrix which scales coordinates of preview size rectangle into the
// camera's native resolution.
scaleMatrix.setRectToRect(previewRect, nativeResRect, Matrix.ScaleToFit.CENTER);
// map the result rectangle to the new coordinates
scaleMatrix.mapRect(resultRect);
// create a matrix which scales coordinates of picture size rectangle into the
// camera's native resolution.
scaleMatrix.setRectToRect(pictureRect, nativeResRect, Matrix.ScaleToFit.CENTER);
// invert it, so that we get the matrix which downscales the rectangle from
// the native resolution to the actual picture size
scaleMatrix.invert(scaleMatrix);
// and map the result rectangle to the coordinates in the picture size rectangle
scaleMatrix.mapRect(resultRect);
在所有这些操作之后,resultRect 将保存相机拍摄的图片内的区域坐标,该坐标对应于您在应用预览中看到的完全相同的图像。您可以通过BitmapRegionDecoder.html#decodeRegion(android.graphics.Rect, android.graphics.BitmapFactory.Options) 方法从图片中剪切此区域。
就是这样。