You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android捕获图片预览正常但本地保存为镜像异常求助

Android前置拍照镜像保存问题解决

你的代码中设置的isReversedHorizontal只是给图片添加了EXIF元数据标记,告知图片查看器需要水平翻转显示,但并非实际修改图片像素数据。很多图库或图片查看应用会忽略这个元数据,导致显示出来的图片仍然是镜像状态。

要彻底解决这个问题,需要在图片保存后实际修改像素数据,将图片水平翻转后重新保存。以下是修改后的代码示例:

val outputOptions = ImageCapture
    .OutputFileOptions
    .Builder(photoFile)
    .build() // 无需设置isReversedHorizontal,后续直接修改像素

imageCapture.takePicture(
    outputOptions, cameraExecutor, object : ImageCapture.OnImageSavedCallback {
        override fun onError(exc: ImageCaptureException) {
            Log.e(TAG, "Photo capture failed: ${exc.message}", exc)
        }

        override fun onImageSaved(output: ImageCapture.OutputFileResults) {
            val savedUri = output.savedUri ?: Uri.fromFile(photoFile)
            Log.d(TAG, "Photo capture succeeded: $savedUri")

            // 仅前置拍照时处理镜像翻转
            if (CameraSelector.LENS_FACING_FRONT == lensFacing) {
                try {
                    // 读取原始图片
                    contentResolver.openInputStream(savedUri)?.use { inputStream ->
                        val bitmap = BitmapFactory.decodeStream(inputStream)
                        // 创建水平翻转的Bitmap
                        val flippedBitmap = Bitmap.createBitmap(
                            bitmap,
                            0,
                            0,
                            bitmap.width,
                            bitmap.height,
                            Matrix().apply { setScale(-1f, 1f) },
                            true
                        )
                        // 重新保存翻转后的图片
                        contentResolver.openOutputStream(savedUri)?.use { outputStream ->
                            flippedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream)
                        }
                        // 回收Bitmap释放内存
                        flippedBitmap.recycle()
                        bitmap.recycle()
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "Failed to flip front camera image: ${e.message}", e)
                }
            }
        }
    })

注意事项

  • 处理高分辨率图片时,可能会出现内存不足问题,可以通过BitmapFactory.Options设置采样率来缩小图片后再处理:
    val options = BitmapFactory.Options().apply {
        inSampleSize = 2 // 采样率,值越大图片越小
    }
    val bitmap = BitmapFactory.decodeStream(inputStream, null, options)
    
  • 如果需要保留原始图片的EXIF信息,需要额外读取并写入翻转后的图片中,可以使用ExifInterface类来处理。

内容的提问来源于stack exchange,提问作者bala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 19:40:05