根据Exif信息纠正图片方向

/ 工具函数:纠正图片方向并保存到新文件
fun correctImageOrientation(originalPath: String?,cachePath:File): String? {
    if(originalPath==null)return null
    // 读取原图的 Exif 方向
    val exif = ExifInterface(originalPath)
    val orientation = exif.getAttributeInt(
        ExifInterface.TAG_ORIENTATION,
        ExifInterface.ORIENTATION_UNDEFINED
    )
    // 计算旋转角度
    val rotationDegrees = when (orientation) {
        ExifInterface.ORIENTATION_ROTATE_90 -> 90f
        ExifInterface.ORIENTATION_ROTATE_180 -> 180f
        ExifInterface.ORIENTATION_ROTATE_270 -> 270f
        else -> 0f // 无需旋转
    }

    // 如果方向正常,直接返回原图路径
    if (rotationDegrees == 0f) return null

    // 创建临时文件保存旋转后的图片
    val tempFile = File.createTempFile("rotated_", ".jpg", cachePath)
    val rotatedBitmap = BitmapFactory.decodeFile(originalPath)
        ?: throw IOException("无法解码图片: $originalPath")

    // 旋转图片
    val matrix = Matrix().apply { postRotate(rotationDegrees) }
    val rotated = Bitmap.createBitmap(
        rotatedBitmap,
        0, 0,
        rotatedBitmap.width,
        rotatedBitmap.height,
        matrix,
        true
    )

    // 保存旋转后的图片,并重置 Exif 方向为正常
    FileOutputStream(tempFile).use { output ->
        rotated.compress(Bitmap.CompressFormat.JPEG, 100, output)
    }
    ExifInterface(tempFile.absolutePath).apply {
        setAttribute(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL.toString())
        saveAttributes()
    }

    // 回收 Bitmap 内存
    rotated.recycle()
    rotatedBitmap.recycle()

    return tempFile.absolutePath
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值