我为这个问题找到了一个非常奇怪的解决方案。当我的相机预览和拍摄的照片具有相同的比例时,生成的照片在所有测试设备上看起来都不错。因此,在获得最佳预览尺寸后,我正在搜索具有相同比例的受支持图片尺寸。
这很奇怪,但它有效。
所以,首先我们需要获得预览尺寸。
protected Size getOptimalPreviewSize(List<Size> sizes, int width, int height) {
Log.d(TAG, String
.format("getOptimalPreviewSize: width = %d, height = %d",
width, height));
final double ASPECT_TOLERANCE = 0.01;
final double targetRatio = (double) 4 / 3d;
if (sizes == null)
return null;
Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = height;
// Try to find an size match aspect ratio and size
double ratio;
Size size;
for (int i = 0; i < sizes.size(); i++) {
size = sizes.get(i);
ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// Cannot find the one match the aspect ratio, ignore the requirement
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (int i = 0; i < sizes.size(); i++) {
size = sizes.get(i);
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
if (optimalSize == null) {
Log.d(TAG, "Optimal size not found");
} else {
Log.d(TAG,
String.format(
"getOptimalPreviewSize result: width = %d, height = %d for input width = %d, height = %d",
optimalSize.width, optimalSize.height, width,
height));
}
return optimalSize;
}
然后我们需要获取图片大小,它与预览具有相同的大小比例。
private Size getOptimalPictureSize() {
if (mCamera == null)
return null;
List<Size> cameraSizes = mCamera.getParameters()
.getSupportedPictureSizes();
Size optimalSize = mCamera.new Size(0, 0);
double previewRatio = (double) mPreviewSize.width / mPreviewSize.height;
for (Size size : cameraSizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - previewRatio) > 0.01f)
continue;
if (size.height > optimalSize.height) {
optimalSize = size;
}
}
if (optimalSize.height == 0) {
for (Size size : cameraSizes) {
if (size.height > optimalSize.height) {
optimalSize = size;
}
}
}
return optimalSize;
}
然后将此尺寸应用于 Camera.Parameters
Size optimalSize = getOptimalPictureSize();
Parameters params = mCamera.getParameters();
Log.d(TAG, "picture size " + optimalSize.width + " "
+ optimalSize.height);
params.setPictureSize(optimalSize.width, optimalSize.height);
mCamera.setParameters(params);