/ 工具函数:纠正图片方向并保存到新文件 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 }
根据Exif信息纠正图片方向
最新推荐文章于 2025-05-21 11:03:04 发布