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

CameraX ImageAnalysis竖屏模式下华为Nova 12 SE图像旋转异常

解决方案:CameraX ImageAnalysis 华为Nova 12 SE 竖屏图像旋转异常

问题原因

华为Nova 12 SE设备上,CameraX返回的imageProxy.imageInfo.rotationDegrees与实际图像物理方向不匹配,导致竖屏捕获的图像被错误旋转90度,直接修改该参数或转换Bitmap无法修正问题。

可行解决方法

1. 手动计算正确旋转角度

结合设备当前窗口方向与CameraX返回的旋转角度,修正得到实际需要的旋转值:

import android.app.Activity
import android.view.Surface
import android.graphics.Matrix
import android.graphics.Bitmap

private fun getCorrectRotation(imageProxy: ImageProxy, activity: Activity): Int {
    val deviceRotation = activity.windowManager.defaultDisplay.rotation
    val cameraRotation = imageProxy.imageInfo.rotationDegrees
    
    return when (deviceRotation) {
        Surface.ROTATION_0 -> cameraRotation
        Surface.ROTATION_90 -> (cameraRotation + 270) % 360
        Surface.ROTATION_180 -> (cameraRotation + 180) % 360
        Surface.ROTATION_270 -> (cameraRotation + 90) % 360
        else -> cameraRotation
    }
}

2. 手动旋转Bitmap后创建InputImage

转换Bitmap后,根据计算出的正确角度手动旋转图像,再传入InputImage(此时旋转参数传0,因为已完成旋转):

fun <T, R> analyzeImageAsync(
    imageProxy: ImageProxy,
    activity: Activity,
    onProcess: (input: InputImage) -> Task<T>,
    transform: (result: T) -> R?
): Deferred<R?> = scope.async {
    val originalBitmap = imageProxy.toBitmap() ?: return@async null
    val correctRotation = getCorrectRotation(imageProxy, activity)
    
    // 执行手动旋转
    val rotatedBitmap = if (correctRotation != 0) {
        val matrix = Matrix().apply { postRotate(correctRotation.toFloat()) }
        Bitmap.createBitmap(originalBitmap, 0, 0, originalBitmap.width, originalBitmap.height, matrix, true)
    } else {
        originalBitmap
    }
    
    val inputImage = InputImage.fromBitmap(rotatedBitmap, 0)
    
    suspendCoroutine { continuation ->
        onProcess(inputImage)
            .addOnSuccessListener { result ->
                continuation.resume(transform(result))
            }.addOnFailureListener { exception ->
                continuation.resumeWithException(exception)
            }
    }
}

3. 确保CameraX ImageAnalysis配置正确

初始化ImageAnalysis时,明确设置目标旋转为当前设备窗口方向:

val imageAnalysis = ImageAnalysis.Builder()
    .setTargetRotation(activity.windowManager.defaultDisplay.rotation)
    // 其他配置(如分辨率、分析模式)
    .build()

imageAnalysis.setAnalyzer(executor) { imageProxy ->
    // 调用analyzeImageAsync处理图像
    lifecycleScope.launch {
        try {
            analyzeImageAsync(imageProxy, this@YourActivity, { inputImage ->
                // 你的图像处理Task逻辑
            }, { result ->
                // 结果转换逻辑
            }).await()
        } finally {
            imageProxy.close()
        }
    }
}

说明

该方案通过绕开设备返回的不准确旋转参数,手动计算并修正图像方向,既能适配华为Nova 12 SE这类存在兼容性问题的设备,又不影响其他正常设备的运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 15:00:00