/ 工具函数:纠正图片方向并保存到新文件
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 -> 90fExifInterface.ORIENTATION_ROTATE_180 -> 180fExifInterface.ORIENTATION_ROTATE_270 -> 270felse -> 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
}