如何拍摄与预览大小相同比例的照片?

6

题目中99.9%的答案如下:

当您搜索由Camera.Parameters#getSupportedPictureSizes()提供的List<Camera.Size>时,请尝试查找与您通过Camera.Parameters.html#setPreviewSize(int,int)设置的相机预览大小具有相同宽高比例的大小,或者尽可能接近。

这很好,但如果我找不到与预览大小相同的宽高比的图片大小(Android无法保证相机支持的每个预览大小都有与其宽高比相同的图片大小),并且所有其他图片大小(尽可能接近)仅会像问题中一样拉伸我的照片,我该如何使照片的宽高比与预览完全相同,即使在Camera.Parameters中设置的图片大小和预览大小具有不同的宽高比?

1个回答

11

我们可以从这个答案中了解到解决此问题的一般方法。简要引用:

我的解决方案是首先将预览选择矩形缩放到本地相机图片大小。现在,我知道本地分辨率的哪个区域包含我想要的内容,我可以对本地分辨率上的矩形进行类似的操作,然后将该矩形缩放到实际由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)方法从图片中裁剪此区域。

就是这样。


1
嘿,我知道这个解决方案有点老了,但也许你可以帮忙——当照片的预览大小比屏幕尺寸时,该如何使其正常工作?所以,屏幕宽度<=预览宽度 && 屏幕高度<=预览高度取决于设备。谢谢。 - Shaked KO
嘿,你怎么获取nativeResRect? - Dima
谢谢。这让我们更清楚地了解从传感器到JPEG的所有层面上正在发生的事情。 - Vikram Rao

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接