在Android中镜像前置摄像头

Edd*_*Edd 7 camera android

在Android中使用前置摄像头拍摄照片时,预览会沿Y轴反射,使看到的图像看起来就像用户正在看镜子一样.我想撤消这种效果(应用第二次反射)或者只是停止自动完成的效果.

我虽然用这个:

Camera mCamera;
....
mCamera.setPreviewCallback(...);
Run Code Online (Sandbox Code Playgroud)

但我真的不知道如何处理压倒一切

onPreviewFrame(byte[] data, Camera camera){...}
Run Code Online (Sandbox Code Playgroud)

什么是我能实现我所描述的最佳方式?

注意我试图将此效果应用于实时预览,而不是已经拍摄的图像.

Sto*_*eev 5

首先使用Camera.open()打开相机实例时,应使用Camera.open打开前置相机(getSpecialFacingCamera())

private int getSpecialFacingCamera() {
    int cameraId = -1;
    // Search for the front facing camera
    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;
}
Run Code Online (Sandbox Code Playgroud)

然后在您的回调方法中,相机数据转换为图像,您可以使用此代码保持正常

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) {
                    // use matrix to reverse image data and keep it normal
                    Matrix mtx = new Matrix();
                    //this will prevent mirror effect
                    mtx.preScale(-1.0f, 1.0f);
                    // Setting post rotate to 90 because image will be possibly in landscape
                    mtx.postRotate(90.f);
                    // Rotating Bitmap , create real image that we want
                    newImage = Bitmap.createBitmap(cameraBitmap, 0, 0, cameraBitmap.getWidth(), cameraBitmap.getHeight(), mtx, true);
                }else{// LANDSCAPE MODE
                    //No need to reverse width and height
                    newImage = Bitmap.createScaledBitmap(cameraBitmap, screenWidth, screenHeight, true);
                    cameraBitmap = newImage;
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

你可以在画布中传递newImage并创建jpeg图像并将其保存在设备上.别忘了相机在Api等级21中已被弃用...


vit*_*lix 2

您可以使用 Matrix 翻转图像数据,例如:

byte[] baImage = null;
Size size = camera.getParameters().getPreviewSize();
ByteArrayOutputStream os = new ByteArrayOutputStream();
YuvImage yuv = new YuvImage(data, ImageFormat.NV21, size.width, size.height, null);
yuv.compressToJpeg(new Rect(0, 0, size.width, size.height), 100, os);
baImage = os.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length);
Matrix matrix = new Matrix(); 
matrix.preScale(-1.0f, 1.0f); 
Bitmap mirroredBitmap = Bitmap.createBitmap(bitmap, 0, 0, size.width, size.height, matrix, false);
Run Code Online (Sandbox Code Playgroud)