关于调用系统相机,图片翻转问题

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 null

      try {
      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方法矫正旋转问题
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容