首先,当您通过Camera.open()打开相机实例时,应该使用Camera.open(getSpecialFacingCamera())来打开前置摄像头。
private int getSpecialFacingCamera() {
int cameraId = -1;
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
cameraId = i;
break;
}
}
return cameraId;
}
然后,在将相机数据转换为图像的回调方法中,您可以使用以下代码来保持其正常。
public void onPictureTaken(byte[] data, Camera camera){
Bitmap newImage = null;
Bitmap cameraBitmap;
if (data != null) {
cameraBitmap = BitmapFactory.decodeByteArray(data, 0, (data != null) ? data.length : 0);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
Matrix mtx = new Matrix();
mtx.preScale(-1.0f, 1.0f);
mtx.postRotate(90.f);
newImage = Bitmap.createBitmap(cameraBitmap, 0, 0, cameraBitmap.getWidth(), cameraBitmap.getHeight(), mtx, true);
}else{
newImage = Bitmap.createScaledBitmap(cameraBitmap, screenWidth, screenHeight, true);
cameraBitmap = newImage;
}
}
}
您可以将newImage传递到画布中,创建jpeg图像并保存在设备上。
不要忘记相机已在21级API中弃用...