我正在使用 CameraX 开发我的 android 应用程序,当我在横向模式或纵向模式下拍摄照片时,捕获并保存的图像是镜像。
我知道 FRONT 摄像头的工作方式相同。但是,如果我想以与拍摄时相同的方式保存照片,该怎么办?
这是我正在使用的 buildUseCase()
代码:
private fun buildUseCases() {
val screenAspectRatio = Rational(width, height)
val screenTargetRotation = display.rotation
//Preview
val previewConfig = PreviewConfig.Builder().apply {
setTargetAspectRatio(screenAspectRatio)
setTargetRotation(screenTargetRotation)
setLensFacing(lensFacing)
}.build()
preview = AutoFitPreviewBuilder.build(previewConfig, this)
//End - Preview
// Set up the capture use case to allow users to take photos
val imageCaptureConfig = ImageCaptureConfig.Builder().apply {
setTargetAspectRatio(screenAspectRatio)
setTargetRotation(screenTargetRotation)
setLensFacing(lensFacing)
setCaptureMode(ImageCapture.CaptureMode.MAX_QUALITY)
}.build()
imageCapture = ImageCapture(imageCaptureConfig)
}
请帮助我更改以获取正确的图像。
注意:相机朝向正面且处于横向模式。
最佳答案
您需要读取创建的图像的 EXIF 数据,并且必须根据要求和需要编写自己的自定义 Controller 。在大多数 Android 和 iOS 设备中,旋转捕获的图像是很正常的,并且必须进行相应的处理。在大多数设备中,相机的默认方向设置为横向模式,因此即使您在纵向模式下拍照,它也会旋转到 90 度。
从 EXIF 数据中,您可以获取图像的旋转度数或镜像的程度,然后您可以在后端处理它。
要旋转图像,您可以尝试
private static Bitmap rotateImageIfRequired(Bitmap img, Uri selectedImage) throws IOException
{
ExifInterface ei = new ExifInterface(selectedImage.getPath());
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotateImage(img, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotateImage(img, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotateImage(img, 270);
default:
return img;
}
}
private static Bitmap rotateImage(Bitmap img, int degree)
{
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
img.recycle();
return rotatedImg;
}
图片翻转问题可以试试这个
public static Bitmap flip(Bitmap src, int type)
{
// create new matrix for transformation
Matrix matrix = new Matrix();
matrix.preScale(-1.0f, 1.0f);
// return transformed image
return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true);
}
然后将图片设置为ImageView为
imgPreview.setImageBitmap(flip(bitmap));
关于android - 如何使用camerax前置摄像头保存正确的旋转图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59896234/