萌萌の初音
萌萌の初音
发布于 2024-01-02 / 940 阅读
0

修复部分android机型拍照后图片方向不对的问题

在使用某些机型调用摄像头拍摄图片后,获得的图片方向不对,这时候我们可用通过ExifInterface类获得图片属性,然后根据图片角度进行处理,直接上代码:

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import androidx.exifinterface.media.ExifInterface

object HandleExifFaceImage {

  fun handleImage(imageFilePath: String): Bitmap? {
    // 从指定路径下读取图片,并获取其EXIF信息
    val exifInterface: ExifInterface = ExifInterface(imageFilePath)
    // 获取图片的旋转信息
    val orientation = exifInterface.getAttributeInt(
      ExifInterface.TAG_ORIENTATION,
      ExifInterface.ORIENTATION_NORMAL
    )
    val degree = when (orientation) {
      ExifInterface.ORIENTATION_ROTATE_90 -> 90
      ExifInterface.ORIENTATION_ROTATE_180 -> 180
      ExifInterface.ORIENTATION_ROTATE_270 -> 270
      else -> 0
    }

    return BitmapFactory.decodeFile(imageFilePath, BitmapFactory.Options())?.let { bitmap ->

      val matrix = Matrix()
      matrix.reset()
      matrix.postRotate(degree.toFloat());

      Bitmap.createBitmap(
        bitmap,
        0,
        0,
        bitmap.width,
        bitmap.height,
        matrix,
        true
      )
    }
  }
}

以上就解决了图片方向不对的问题