I am working with the front camera in a Flutter app, and I noticed that on some Android devices, the preview appears mirrored, while on others, it looks correct. I need a reliable way to detect whether the front camera is mirroring.
What I have tried:
- Checking sensorOrientation in CameraController.description:
I assumed that devices with a
sensorOrientation
of90
or270
would mirror the front camera, but this method is unreliable.
bool isFrontCameraMirrored() {
if (_cameraController?.description.lensDirection == CameraLensDirection.front) {
int sensorOrientation = _cameraController?.description.sensorOrientation ?? 0;
// Devices with sensor orientation 90 or 270 are likely to mirror the front camera.
return sensorOrientation == 90 || sensorOrientation == 270;
}
return false;
}
Issue: This does not work because I have two different devices with a sensorOrientation
of 270
—one is mirrored, and the other is not.
- Taking a picture and checking pixel differences: I tried capturing an image and comparing pixels on the left and right sides to detect mirroring.
bool checkHorizontalMirroring(img.Image image) {
int width = image.width;
int height = image.height;
var leftPixel = image.getPixel(10, height ~/ 2);
var rightPixel = image.getPixel(width - 10, height ~/ 2);
return leftPixel != rightPixel;
}
Issue: This method always returns true, even when the image is not mirrored.
How I want to use this detection result:
Once I detect whether the camera is mirroring, I want to use _isMirroredHorizontally
in my UI like this:
_isMirroredHorizontally
? Positioned.fill(
child: Transform.flip(
flipX: true,
child: CameraPreview(_cameraController!),
),
)
: Transform.scale(
scale: 1 / tempScale,
child: Center(
child: CameraPreview(_cameraController!),
),
),