我们在自己的应用中实现了自定义相机功能。这在除了三星galaxy S4 mini之外的nexus4,5,samsung s3,s4等所有设备上都运行良好。问题是图像仅在前置摄像头中伸展,但它在该设备的后置摄像头中工作良好。
对于三星galaxy s4 mini,屏幕尺寸为540X960,支持预览尺寸为1280x720。宽高比也相同,但我们正面临图像拉伸问题。我尝试了很多,但我无法解决这个问题,特别是在三星galaxy s4 mini的前置摄像头。请任何人帮助我。
Code
int currentCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
Camera camera = Camera.open(currentCameraId);
try {
camera.setPreviewDisplay(surfaceHolder);
Camera.Parameters parameters = camera.getParameters();
parameters.setPictureFormat(PixelFormat.JPEG);
parameters.set("orientation", "portrait");
camera.setDisplayOrientation(90);
parameters.setRotation(270);
Display display = getWindowManager().getDefaultDisplay();
int widthd = display.getWidth(); // deprecated
int heightd = display.getHeight();
List<Camera.Size> previewSizes = parameters.getSupportedPreviewSizes();
List<Camera.Size> pictureSizes = parameters.getSupportedPictureSizes();
Camera.Size mPreviewSize = getOptimalPreviewSize(previewSizes, widthd, heightd);
Camera.Size mpicSize = getOptimalPreviewSize(pictureSizes, widthd, heightd);
parameters.setPreviewSize(mPreviewSize.width,mPreviewSize.height);
parameters.setPictureSize(mpicSize.width,mpicSize.height);
camera.setParameters(parameters);
} catch (IOException exception) {
camera.release();
}
camera.startPreview();
请参阅以下代码以计算最佳尺寸。
private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w,
int h) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio = (double) h / w;
if (sizes == null)
return null;
Camera.Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
for (Camera.Size size : sizes) {
double 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);
}
}
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Camera.Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}