/ 工具函数:纠正图片方向并保存到新文件
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
}
12-24
1161
1161
11-18
5032
5032
08-30
1068
1068
06-24
3015
3015

被折叠的 条评论
为什么被折叠?



