package com.jitu.express.thailand.outfield.ui.face
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.media.ExifInterface
import java.io.File
/**
Bitmap EXIF工具类
-
用于处理图片的EXIF信息,自动旋转和镜像校正
*/
object BitmapExifUtil {/**
从文件读取 EXIF 信息,自动旋转 & 镜像校正
@param file 拍照保存的文件
-
@return 方向正确的 Bitmap
*/
fun decodeBitmapWithExif(file: File): Bitmap? {
val options = BitmapFactory.Options().apply {
inSampleSize = 2 // 减少内存占用
}
var bitmap = BitmapFactory.decodeFile(file.absolutePath, options) ?: return nulltry {
val exif = ExifInterface(file.absolutePath)
val orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL
)bitmap = when (orientation) { ExifInterface.ORIENTATION_ROTATE_90 -> rotateBitmap(bitmap, 90f) ExifInterface.ORIENTATION_ROTATE_180 -> rotateBitmap(bitmap, 180f) ExifInterface.ORIENTATION_ROTATE_270 -> rotateBitmap(bitmap, 270f) ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> flipBitmapHorizontally(bitmap) ExifInterface.ORIENTATION_FLIP_VERTICAL -> flipBitmapVertically(bitmap) ExifInterface.ORIENTATION_TRANSPOSE -> { // 横向翻转后再旋转 90 rotateBitmap(flipBitmapHorizontally(bitmap), 90f) } ExifInterface.ORIENTATION_TRANSVERSE -> { // 横向翻转后再旋转 270 rotateBitmap(flipBitmapHorizontally(bitmap), 270f) } else -> bitmap }} catch (e: Exception) {
e.printStackTrace()
}return bitmap
}
/**
- 旋转 Bitmap
*/
private fun rotateBitmap(bitmap: Bitmap, degree: Float): Bitmap {
val matrix = Matrix()
matrix.postRotate(degree)
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
}
/**
- 水平翻转 Bitmap
*/
fun flipBitmapHorizontally(bitmap: Bitmap): Bitmap {
val matrix = Matrix()
matrix.preScale(-1f, 1f)
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
}
/**
- 垂直翻转 Bitmap
*/
private fun flipBitmapVertically(bitmap: Bitmap): Bitmap {
val matrix = Matrix()
matrix.preScale(1f, -1f)
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
}
}
----------调用decodeBitmapWithExif方法矫正旋转问题